Verified contractPartialMIT
Listings
Address0x11f09e7eed242fad875d3565b3d9ca8aade445ae
- Balance
0 ETH
- Transactions
14
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 123 runs
- EVM version
- cancun
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,638,261
- Creation transaction
- 0x8a99cc352f…c682c55739
41 files
- src/contracts/Listings.solmain56.33 KB
- lib/solady/src/auth/Ownable.sol12.51 KB
- lib/solady/src/utils/ReentrancyGuard.sol2.33 KB
- lib/solady/src/utils/SafeTransferLib.sol26.39 KB
- lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol10.8 KB
- lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.93 KB
- lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/v4-hooks-public/lib/v4-core/src/interfaces/IHooks.sol8.23 KB
- lib/v4-hooks-public/lib/v4-core/src/interfaces/external/IERC20Minimal.sol3.04 KB
- lib/v4-hooks-public/lib/v4-core/src/libraries/CustomRevert.sol5.17 KB
- lib/v4-hooks-public/lib/v4-core/src/libraries/SafeCast.sol2.27 KB
- lib/v4-hooks-public/lib/v4-core/src/types/BalanceDelta.sol2.34 KB
- lib/v4-hooks-public/lib/v4-core/src/types/BeforeSwapDelta.sol1.47 KB
- lib/v4-hooks-public/lib/v4-core/src/types/Currency.sol5.4 KB
- lib/v4-hooks-public/lib/v4-core/src/types/PoolId.sol539 B
- lib/v4-hooks-public/lib/v4-core/src/types/PoolKey.sol805 B
- lib/v4-hooks-public/lib/v4-core/src/types/PoolOperation.sol907 B
- src/contracts/TokenEscrow.sol2.75 KB
- src/contracts/libraries/NFTTransferLib.sol23.63 KB
- src/interfaces/Enums.sol809 B
- src/interfaces/ICollectionLaunchGate.sol2.52 KB
- src/interfaces/ICollectionToken.sol496 B
- src/interfaces/ICryptoKitties.sol916 B
- src/interfaces/ICryptoPunksMarket.sol1.15 KB
- src/interfaces/IListings.sol15.71 KB
- src/interfaces/ILocker.sol8.08 KB
- src/interfaces/ILockerManager.sol291 B
- src/interfaces/INFTXV4Hook.sol12.88 KB
- src/interfaces/INotifier.sol5.66 KB
- src/interfaces/ISubscriber.sol4.43 KB
- src/interfaces/ITaxCalculator.sol201 B
- src/interfaces/ITokenEscrow.sol944 B
- src/interfaces/lssvm2/CurveErrorCodes.sol459 B
- src/interfaces/lssvm2/ICurve.sol3.84 KB
- src/interfaces/lssvm2/ILSSVMPair.sol1.1 KB
- src/interfaces/lssvm2/ILSSVMPairFactoryLike.sol852 B
- src/interfaces/utils/ICollectionShutdown.sol6.25 KB
src/contracts/Listings.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Ownable} from 'solady/auth/Ownable.sol';
import {ReentrancyGuard} from 'solady/utils/ReentrancyGuard.sol';
import {SafeTransferLib} from 'solady/utils/SafeTransferLib.sol';
import {TokenEscrow} from 'nftx/TokenEscrow.sol';
import {NFTTransferLib} from 'nftx/libraries/NFTTransferLib.sol';
import {Enums} from 'nftx-interfaces/Enums.sol';
import {ICollectionToken} from 'nftx-interfaces/ICollectionToken.sol';
import {IListings} from 'nftx-interfaces/IListings.sol';
import {ILocker} from 'nftx-interfaces/ILocker.sol';
import {INFTXV4Hook} from 'nftx-interfaces/INFTXV4Hook.sol';
import {ITaxCalculator} from 'nftx-interfaces/ITaxCalculator.sol';
/**
* Listings over NFTs held in the {Locker}. Depositing an NFT mints exactly {FLOOR_VALUE} of the
* collection's ERC20; a listing prices that same NFT above the floor and prepays tax on the
* premium for a fixed window. Liquid listings can be modified and cancelled; dutch listings, and
* liquid listings past their window, decay back towards the floor and can only be filled or
* relisted.
*/
contract Listings is IListings, Ownable, ReentrancyGuard, TokenEscrow {
/// Transient slots accumulating per-owner fill results across a {fillListings} batch
bytes32 private constant FILL_FEE = 0xa40c0092c38dd399f81cbdededd4c56dc816ce700d2ef20bf50ba8480186c5bf;
bytes32 private constant FILL_PRICE = 0x9547ee3353571b86e0e79a9ff81447cc69303c44482a02ebfc5d7cca4dd94998;
bytes32 private constant FILL_REFUND = 0x82cd2f49fb2388af88155c0aea5209e274b39b84940eddd1580d670af04dc096;
/// Structural lower bound on `floorMultiple`, which is expressed in hundredths of the floor
uint internal constant MIN_FLOOR_MULTIPLE = 100;
/// The CollectionToken value of a single NFT, and therefore the hard ceiling on the prepaid
/// tax a single listing may hold. `cancelListings` funds its burn as
/// `(FLOOR_VALUE * n) - refund`, so a listing holding more than this underflows that
/// subtraction and locks its owner out of their own exit. See {_assertTaxWithinFloorValue}.
uint internal constant FLOOR_VALUE = 1 ether;
/// The {Locker} that custodies every listed ERC721
ILocker public immutable locker;
/// Listing rows, keyed by collection and tokenId
mapping(address _collection => mapping(uint _tokenId => Listing _listing)) private _listings;
/// Open listings per collection; {CollectionShutdown} refuses to execute while this is non-zero
mapping(address _collection => uint _count) public listingCount;
/// The tax calculator used when a collection has no per-collection override
ITaxCalculator public defaultTaxCalculator;
/// Per-collection tax-calculator overrides. A zero address will use {defaultTaxCalculator}
mapping(address _collection => ITaxCalculator) public collectionTaxCalculator;
/// Default {ListingConfig} for collections without a registered override
ListingConfig public defaultListingConfig;
/// Per-collection {ListingConfig} overrides
mapping(address _collection => ListingConfig) public collectionListingConfig;
/**
* Binds the contract to its {Locker} and seeds the protocol-wide defaults.
*
* @param _locker The {Locker} that will custody every listed ERC721; cannot be `address(0)`
* @param _defaultListingConfig The config every collection without an override resolves to,
* run through {_validateListingConfig} before it is stored
* @param _defaultTaxCalculator The calculator every collection without an override prices
* against; cannot be `address(0)`
* @param _owner The initial {Ownable} owner, which holds the four configuration setters
*/
constructor(ILocker _locker, ListingConfig memory _defaultListingConfig, ITaxCalculator _defaultTaxCalculator, address _owner) {
if (address(_locker) == address(0)) revert LockerIsZeroAddress();
locker = _locker;
// Every collection without an override resolves to this config, so it goes through the
// same validator the setters use rather than being trusted at deployment.
_validateListingConfig(_defaultListingConfig);
defaultListingConfig = _defaultListingConfig;
if (address(_defaultTaxCalculator) == address(0)) revert TaxCalculatorIsZeroAddress();
defaultTaxCalculator = _defaultTaxCalculator;
_initializeOwner(_owner);
}
/**
* Resolves the effective {ITaxCalculator} for a collection: the per-collection override when
* one is set, else the {defaultTaxCalculator}.
*
* @param _collection The ERC721 collection to resolve the calculator for
*
* @return calc_ The calculator that prices this collection's listings
*/
function taxCalculator(address _collection) public view returns (ITaxCalculator calc_) {
calc_ = collectionTaxCalculator[_collection];
if (address(calc_) == address(0)) {
calc_ = defaultTaxCalculator;
}
}
/**
* Resolves the effective {ListingConfig} for a collection.
*
* @dev `maxFloorMultiple != 0` is the sentinel for a registered override. The override is
* all-or-nothing: a cleared one falls back wholesale to {defaultListingConfig}, with no
* per-field merging.
*
* @param _collection The ERC721 collection to resolve the config for
*
* @return config_ The config that bounds this collection's listings
*/
function listingConfig(address _collection) public view returns (ListingConfig memory config_) {
config_ = collectionListingConfig[_collection];
if (config_.maxFloorMultiple == 0) {
config_ = defaultListingConfig;
}
}
/**
* Sets the protocol-wide default tax calculator, used by any collection without an override.
*
* @param _taxCalculator The new default calculator; cannot be `address(0)`
*/
function setDefaultTaxCalculator(address _taxCalculator) public onlyOwner {
if (_taxCalculator == address(0)) {
revert TaxCalculatorIsZeroAddress();
}
defaultTaxCalculator = ITaxCalculator(_taxCalculator);
emit DefaultTaxCalculatorUpdated(_taxCalculator);
}
/**
* Sets (or clears) a per-collection tax-calculator override.
*
* @param _collection The ERC721 collection the override applies to
* @param _taxCalculator The override calculator, or `address(0)` to clear it and fall back to
* {defaultTaxCalculator} on subsequent reads
*/
function setCollectionTaxCalculator(address _collection, address _taxCalculator) public onlyOwner {
collectionTaxCalculator[_collection] = ITaxCalculator(_taxCalculator);
emit CollectionTaxCalculatorUpdated(_collection, _taxCalculator);
}
/**
* Sets the protocol-wide default {ListingConfig}, which must pass {_validateListingConfig}.
*
* @param _config The new default config, applied to every collection without an override
*/
function setDefaultListingConfig(ListingConfig calldata _config) public onlyOwner {
_validateListingConfig(_config);
defaultListingConfig = _config;
emit DefaultListingConfigUpdated(_config);
}
/**
* Sets (or clears) a per-collection {ListingConfig} override.
*
* @param _collection The ERC721 collection the override applies to
* @param _config The override config, or a struct with `maxFloorMultiple == 0` to clear the
* override and fall back to {defaultListingConfig}
*/
function setCollectionListingConfig(address _collection, ListingConfig calldata _config) public onlyOwner {
if (_config.maxFloorMultiple != 0) {
_validateListingConfig(_config);
collectionListingConfig[_collection] = _config;
}
// A zero `maxFloorMultiple` is the clear sentinel, not a config to store
else {
delete collectionListingConfig[_collection];
}
emit CollectionListingConfigUpdated(_collection, _config);
}
/**
* Cross-field invariants enforced on every non-zero {ListingConfig} write, kept in one place
* so the default and per-collection paths cannot drift apart.
*
* @dev Takes `memory` rather than `calldata` so the constructor, whose argument is
* necessarily `memory`, can reach it; the setters pay a copy on the way in.
*
* @dev The dutch and liquid duration windows must not overlap, because {getListingType}
* discriminates the two purely on `duration` and an overlap makes that answer ambiguous.
*
* @param _config The config to check; reverts with {InvalidListingConfig} on the first rule it
* fails
*/
function _validateListingConfig(ListingConfig memory _config) private pure {
// At or below the structural minimum nothing would be listable
if (uint(_config.maxFloorMultiple) <= MIN_FLOOR_MULTIPLE) revert InvalidListingConfig();
if (_config.minDutchDuration == 0) revert InvalidListingConfig();
if (_config.minDutchDuration > _config.maxDutchDuration) revert InvalidListingConfig();
if (_config.minLiquidDuration == 0) revert InvalidListingConfig();
if (_config.minLiquidDuration > _config.maxLiquidDuration) revert InvalidListingConfig();
// The two windows must stay disjoint, per the note above
if (_config.maxDutchDuration >= _config.minLiquidDuration) revert InvalidListingConfig();
if (_config.liquidDutchDuration == 0) revert InvalidListingConfig();
}
/**
* Getter for the `_listings` mapping.
*
* @param _collection The ERC721 collection the token belongs to
* @param _tokenId The token ID to read the listing row of
*
* @return The stored listing, zeroed when the token is a floor item with no row of its own
*/
function listings(address _collection, uint _tokenId) public view returns (Listing memory) {
return _listings[_collection][_tokenId];
}
/**
* Creates listings from grouped {CreateListing} structures.
*
* Every tokenId in a group shares one listing shape, so the group is validated and priced
* once and the tax multiplied by the token count. A listing row is still written per tokenId
* so that individual listings stay independently cancellable.
*
* @param _createListings The groups to create; the caller must hold every tokenId listed and
* have approved this contract to transfer them
*/
function createListings(CreateListing[] calldata _createListings) public nonReentrant lockerNotPaused {
// Loop variables
uint taxRequired;
uint tokensIdsLength;
uint tokensReceived;
// Loop over the unique listing structures
for (uint i; i < _createListings.length; ++i) {
CreateListing calldata listing = _createListings[i];
// `_mapListings` stamps `created` to the current block, so validate, price and report
// against the struct exactly as it will be stored, not the `created` in calldata.
Listing memory pending = listing.listing;
pending.created = uint40(block.timestamp);
_validateCreateListing(listing.collection, pending);
tokensIdsLength = listing.tokenIds.length;
tokensReceived = _mapListings(listing, tokensIdsLength);
// The mint above is the whole tax budget, which is what holds a listing to
// {FLOOR_VALUE} of prepaid tax without an explicit assertion on this path
taxRequired = getListingTaxRequired(pending, listing.collection) * tokensIdsLength;
if (taxRequired > tokensReceived) revert InsufficientTax(tokensReceived, taxRequired);
unchecked {
tokensReceived -= taxRequired;
}
unchecked {
listingCount[listing.collection] += tokensIdsLength;
}
_depositNftsAndReceiveTokens(listing, tokensReceived);
emit ListingsCreated(
listing.collection,
listing.tokenIds,
pending,
getListingType(listing.collection, pending),
tokensReceived,
taxRequired,
msg.sender
);
}
}
/**
* Deposits the group's NFTs into the {Locker} and forwards the post-tax share of the minted
* ERC20 on to the listing owner.
*
* @param _listing The group being created, supplying the collection, tokenIds and owner
* @param _tokensReceived The post-tax remainder of the mint, forwarded to the listing owner
*/
function _depositNftsAndReceiveTokens(CreateListing calldata _listing, uint _tokensReceived) private {
address collection = _listing.collection;
NFTTransferLib.pullBatch(collection, msg.sender, _listing.tokenIds);
NFTTransferLib.approveOperatorForTokens(collection, address(locker), _listing.tokenIds);
// Part of the minted supply stays here as prepaid tax, so the mint is directed at this
// contract and only the remainder is forwarded on below
locker.deposit(collection, _listing.tokenIds, address(this));
// On the ERC721 branch the grant above is a collection-wide `setApprovalForAll`, so
// revoke it here to keep the {Locker}'s authority scoped to this call frame
NFTTransferLib.revokeOperatorApproval(collection, address(locker));
locker.collectionToken(collection).transfer(_listing.listing.owner, _tokensReceived);
}
/**
* Writes a listing row for every tokenId in the group and returns the ERC20 the matching
* {Locker} deposit will mint against them.
*
* @param _createListing The group being created, supplying the collection, the tokenIds and
* the listing shape copied into every row
* @param _tokenIds The number of token IDs to map, not the IDs themselves
*
* @return tokensReceived_ The collection token the deposit mints, one {FLOOR_VALUE} per token
*/
function _mapListings(CreateListing calldata _createListing, uint _tokenIds) private returns (uint tokensReceived_) {
for (uint i; i < _tokenIds; ++i) {
_listings[_createListing.collection][_createListing.tokenIds[i]] = Listing({
owner: _createListing.listing.owner,
created: uint40(block.timestamp),
duration: _createListing.listing.duration,
floorMultiple: _createListing.listing.floorMultiple
});
}
// The {Locker} always mints exactly one collection token per deposited ERC721
tokensReceived_ = _tokenIds * FLOOR_VALUE;
}
/**
* Validates a listing against the collection's resolved {ListingConfig}, reverting on the
* first rule it fails.
*
* @dev Takes the resolved {Listing} rather than the raw {CreateListing} because `created`
* participates in {getListingType}: validating a value other than the one written would let
* a caller qualify under one classification and store another.
*
* @param _collection The ERC721 collection being listed against; must be initialized in the
* {Locker} and supplies the {ListingConfig} every bound below is read from
* @param _listing The listing exactly as it will be stored
*/
function _validateCreateListing(address _collection, Listing memory _listing) private view {
if (!locker.collectionInitialized(_collection)) revert CollectionNotInitialized();
// A zero owner is the floor-item sentinel everywhere else, so it can never be stored here
if (_listing.owner == address(0)) revert ListingOwnerIsZero();
// Resolved once; every branch below reads this copy rather than re-entering storage
ListingConfig memory config = listingConfig(_collection);
if (_listing.floorMultiple <= MIN_FLOOR_MULTIPLE) revert FloorMultipleMustBeAbove100(_listing.floorMultiple);
if (_listing.floorMultiple > config.maxFloorMultiple) {
revert FloorMultipleExceedsMax(_listing.floorMultiple, config.maxFloorMultiple);
}
// The type is derived from `duration`, then `duration` is re-checked against that type's
// window; a freshly created listing can never be `NONE`, so the final branch is unreachable
Enums.ListingType listingType = getListingType(_collection, _listing);
if (listingType == Enums.ListingType.DUTCH) {
if (_listing.duration < config.minDutchDuration) {
revert ListingDurationBelowMin(_listing.duration, config.minDutchDuration);
}
if (_listing.duration > config.maxDutchDuration) {
revert ListingDurationExceedsMax(_listing.duration, config.maxDutchDuration);
}
} else if (listingType == Enums.ListingType.LIQUID) {
if (_listing.duration < config.minLiquidDuration) {
revert ListingDurationBelowMin(_listing.duration, config.minLiquidDuration);
}
if (_listing.duration > config.maxLiquidDuration) {
revert ListingDurationExceedsMax(_listing.duration, config.maxLiquidDuration);
}
} else {
revert InvalidListingType();
}
}
/**
* Changes the duration and/or price of multiple liquid listings. Each old prepaid window is
* settled first and the refunds are netted against the new charge, so only the difference
* between the two ever moves.
*
* @param _collection The ERC721 collection every entry belongs to
* @param _modifyListings The per-token changes to apply; a zero `duration` leaves that
* listing's duration alone, and an entry that changes nothing is skipped
* @param _payTaxWithEscrow Whether to draw any shortfall from the caller's escrow balance
*
* @return taxRequired_ The new prepaid tax across every modified listing
* @return refund_ Whatever survives of the refunds after paying `taxRequired_`
*/
function modifyListings(address _collection, ModifyListing[] calldata _modifyListings, bool _payTaxWithEscrow)
public
nonReentrant
lockerNotPaused
returns (uint taxRequired_, uint refund_)
{
uint fees;
// Every iteration bounds against the same collection, so resolve the config once
ListingConfig memory config = listingConfig(_collection);
for (uint i; i < _modifyListings.length; ++i) {
ModifyListing memory params = _modifyListings[i];
Listing storage listing = _listings[_collection][params.tokenId];
// Only liquid listings are modifiable, and an expired one has already reclassified
// as DUTCH, so this also rejects listings past their window
if (getListingType(_collection, listing) != Enums.ListingType.LIQUID) revert InvalidListingType();
if (listing.owner != msg.sender) revert CallerIsNotOwner(listing.owner);
// A no-op entry must not restart the prepaid window below
if (params.duration == 0 && params.floorMultiple == listing.floorMultiple) {
continue;
}
{
// Settle the old window; `false` defers the token movements to the batch totals below
(uint _fees, uint _refund) = _resolveListingTax(listing, _collection, false);
emit ListingFeeCaptured(_collection, params.tokenId, _fees);
fees += _fees;
refund_ += _refund;
}
{
// Captured for the `ListingExtended` event emitted once every field has settled below
uint32 previousDuration = listing.duration;
// A zero `duration` means "leave the duration alone", not "expire immediately"
if (params.duration != 0) {
if (params.duration < config.minLiquidDuration) {
revert ListingDurationBelowMin(params.duration, config.minLiquidDuration);
}
if (params.duration > config.maxLiquidDuration) {
revert ListingDurationExceedsMax(params.duration, config.maxLiquidDuration);
}
listing.duration = params.duration;
}
if (params.floorMultiple != listing.floorMultiple) {
if (params.floorMultiple <= MIN_FLOOR_MULTIPLE) {
revert FloorMultipleMustBeAbove100(params.floorMultiple);
}
if (params.floorMultiple > config.maxFloorMultiple) {
revert FloorMultipleExceedsMax(params.floorMultiple, config.maxFloorMultiple);
}
emit ListingFloorMultipleUpdated(_collection, params.tokenId, listing.floorMultiple, params.floorMultiple);
listing.floorMultiple = params.floorMultiple;
}
// Restart the prepaid window on every modification, not only those that change
// `duration`. The old window was settled above and the charge below is a full
// `duration` of tax, and every tax path assumes a listing's prepayment covers
// `duration` measured from `created`, so `created` has to move with the charge.
listing.created = uint40(block.timestamp);
emit ListingExtended(_collection, params.tokenId, previousDuration, listing.duration);
}
// Held to the same per-token ceiling `createListings` enforces, so the owner can
// still afford to cancel afterwards
uint listingTax = getListingTaxRequired(listing, _collection);
_assertTaxWithinFloorValue(listingTax);
taxRequired_ += listingTax;
}
ICollectionToken collectionToken = locker.collectionToken(_collection);
// Net the refunds against the new charge so only the difference is pulled or returned
if (taxRequired_ > refund_) {
unchecked {
payTaxWithEscrow(address(collectionToken), taxRequired_ - refund_, _payTaxWithEscrow);
}
refund_ = 0;
} else {
unchecked {
refund_ -= taxRequired_;
}
}
_depositCollectionFees(_collection, collectionToken, fees);
if (refund_ != 0) {
_deposit(msg.sender, address(collectionToken), refund_);
}
}
/**
* Transfers a single listing to a new owner, who then holds the right to modify or cancel it
* and receives its proceeds and tax refunds.
*
* @param _collection The ERC721 collection the listing belongs to
* @param _tokenId The listed token ID, whose listing must currently be owned by the caller
* @param _newOwner The address taking the listing over; cannot be `address(0)`, which is the
* floor-item sentinel
*/
function transferOwnership(address _collection, uint _tokenId, address payable _newOwner) public nonReentrant lockerNotPaused {
// A zero owner would silently demote the listing to a floor item
if (_newOwner == address(0)) revert NewOwnerIsZero();
Listing storage listing = _listings[_collection][_tokenId];
if (listing.owner != msg.sender) revert CallerIsNotOwner(listing.owner);
listing.owner = _newOwner;
emit ListingTransferred(_collection, _tokenId, msg.sender, _newOwner);
}
/**
* Cancels listings, returning each NFT to its owner in exchange for burning the
* {FLOOR_VALUE} minted against it, funded net of the unused prepaid tax refunded back.
*
* @param _collection The ERC721 collection every token belongs to
* @param _tokenIds The listed token IDs to cancel; each must be LIQUID and owned by the caller
* @param _payTaxWithEscrow Whether to draw the burn shortfall from the caller's escrow balance
*/
function cancelListings(address _collection, uint[] memory _tokenIds, bool _payTaxWithEscrow) public nonReentrant lockerNotPaused {
uint fees;
uint refund;
for (uint i; i < _tokenIds.length; ++i) {
uint _tokenId = _tokenIds[i];
Listing memory listing = _listings[_collection][_tokenId];
if (listing.owner != msg.sender) revert CallerIsNotOwner(listing.owner);
// Dutch listings cannot be cancelled. An expired liquid listing has already
// reclassified as DUTCH, so this rejects listings past their window too.
Enums.ListingType listingType = getListingType(_collection, listing);
if (listingType != Enums.ListingType.LIQUID) revert CannotCancelListingType();
// Settle the prepaid window; `false` defers the token movements to the totals below
(uint _fees, uint _refund) = _resolveListingTax(listing, _collection, false);
emit ListingFeeCaptured(_collection, _tokenId, _fees);
fees += _fees;
refund += _refund;
delete _listings[_collection][_tokenId];
locker.withdrawToken(_collection, _tokenId, msg.sender);
}
ICollectionToken collectionToken = locker.collectionToken(_collection);
// Burn back the ERC20 minted at creation. The refund already sits in this contract, so
// only the shortfall is collected from the caller; a listing whose prepaid tax exceeded
// {FLOOR_VALUE} would underflow here, which is what that ceiling exists to prevent.
uint requiredAmount = (FLOOR_VALUE * _tokenIds.length) - refund;
payTaxWithEscrow(address(collectionToken), requiredAmount, _payTaxWithEscrow);
collectionToken.burn(requiredAmount + refund);
_depositCollectionFees(_collection, collectionToken, fees);
// Deliberately checked: this counter gates {CollectionShutdown}, so an accounting error
// must revert here rather than wrap to an enormous value and block shutdown forever.
listingCount[_collection] -= _tokenIds.length;
emit ListingsCancelled(_collection, _tokenIds);
}
/**
* Force-closes a listing whose backing NFT is no longer held by the {Locker}.
*
* An NFT can leave the {Locker} without passing through this contract: a collection admin
* burn, an upgradeable implementation rewriting ownership, or {AirdropRecipient.claimAirdrop}'s
* ERC721 branch. The listing it backed then has no exit — `fillListings` and `relist` fail the
* availability check, `cancelListings` reverts inside `locker.withdrawToken` — so
* `listingCount` never reaches zero and {CollectionShutdown.execute} is blocked forever. This
* is the reconcile path, permissionless because the state it repairs blocks a collection-wide
* operation.
*
* @dev `nonReentrant` is load-bearing, not decorative: `createListings` writes listing rows
* before depositing the NFTs, so mid-transaction a live row exists with the token still
* outside the {Locker}.
*
* @dev The staleness verdict is the collection's own `ownerOf` answer, so a collection that
* reverts, pauses or lies can make healthy listings closable. Bounded on the consequence side:
* prepaid tax settles exactly as `cancelListings` settles it, so a false positive costs the
* owner the asking premium — never the {FLOOR_VALUE} backing they already hold — and leaves
* the NFT in the {Locker} as a floor item.
*
* @dev Deliberately not gated on `locker.collectionInitialized`: a sunset collection is
* precisely the one likely to carry stale rows.
*
* @param _collection The ERC721 collection the stale listing was created against
* @param _tokenId The listed token ID whose backing NFT the {Locker} no longer holds
*/
function closeStaleListing(address _collection, uint _tokenId) external nonReentrant lockerNotPaused {
Listing memory listing = _listings[_collection][_tokenId];
// A floor item has no row and was never counted; without this an unlisted tokenId would
// decrement `listingCount` against a listing that does not exist
if (listing.owner == address(0)) revert ListingDoesNotExist(_collection, _tokenId);
// The sole precondition, subject to the collection answering honestly
if (_lockerHoldsToken(_collection, _tokenId)) revert ListingIsNotStale(_collection, _tokenId);
// Drop the row and the counter before any external call. Deliberately checked: an
// underflow must revert rather than wrap and block shutdown permanently.
delete _listings[_collection][_tokenId];
listingCount[_collection] -= 1;
// Settle the prepaid tax as every other exit does. `sunsetCollection` clears the
// collection's {CollectionToken} mapping, so post-sunset there is nothing to move — skip
// the settlement rather than revert, and still repair the row and the counter.
uint fees;
uint refund;
if (address(locker.collectionToken(_collection)) != address(0)) {
(fees, refund) = _resolveListingTax(listing, _collection, true);
}
if (fees != 0) {
emit ListingFeeCaptured(_collection, _tokenId, fees);
}
emit ListingClosedAsStale(_collection, _tokenId, listing.owner, fees, refund);
}
/**
* Fills a single listing: releases the NFT to `_recipient` and books its price, fee and tax
* refund.
*
* @dev Results accumulate into transient storage (`FILL_PRICE`, `FILL_FEE`, `FILL_REFUND`)
* rather than being returned, so {fillListings} can total them across a whole owner group and
* settle once. The slots are private to this contract and cleared per group.
*
* @param _collection The ERC721 collection the token belongs to
* @param _collectionToken The collection's ERC20, resolved once by {fillListings} and passed
* down; this frame books its figures transiently and never moves tokens itself
* @param _tokenId The token ID being filled, either a listing or a bare floor item
* @param _recipient The address the {Locker} releases the NFT to
*/
function _fillListing(address _collection, address _collectionToken, uint _tokenId, address _recipient) private {
(bool isAvailable, uint price) = getListingPrice(_collection, _tokenId);
assembly {
tstore(FILL_PRICE, add(tload(FILL_PRICE), price))
}
if (!isAvailable) revert ListingNotAvailable();
// A zero owner is a floor item: no listing row, so no tax and no counter to settle
if (_listings[_collection][_tokenId].owner != address(0)) {
// Settle the prepaid window; `false` defers the token movements to {fillListings}
(uint fee, uint refund) = _resolveListingTax(_listings[_collection][_tokenId], _collection, false);
emit ListingFeeCaptured(_collection, _tokenId, fee);
assembly {
tstore(FILL_FEE, add(tload(FILL_FEE), fee))
tstore(FILL_REFUND, add(tload(FILL_REFUND), refund))
}
// Deliberately checked: this counter gates {CollectionShutdown}, so an underflow must
// revert rather than wrap to an enormous value and block shutdown permanently.
listingCount[_collection] -= 1;
delete _listings[_collection][_tokenId];
}
locker.withdrawToken(_collection, _tokenId, _recipient);
}
/**
* Fills multiple listings with the collection's ERC20. `params.tokenIdsOut` is grouped by
* listing owner so each owner's proceeds settle in a single escrow deposit.
*
* @param params The collection, the owner-grouped `tokenIdsOut`, the `recipient` the NFTs are
* released to, and a `maxSpend` ceiling on the buyer's cost that zero opts out of
*
* @return totalBurn_ The number of NFTs filled, not an ERC20 amount; the burn it drives is
* `totalBurn_ * FLOOR_VALUE`
*/
function fillListings(FillListingsParams calldata params) public nonReentrant lockerNotPaused returns (uint totalBurn_) {
address collection = params.collection;
ICollectionToken _collectionToken = locker.collectionToken(collection);
if (address(_collectionToken) == address(0)) revert InvalidCollection();
// Loop variables
address owner;
uint ownerReceives;
uint refundAmount;
uint totalPrice;
for (uint ownerIndex; ownerIndex < params.tokenIdsOut.length; ++ownerIndex) {
uint ownerIndexTokens = params.tokenIdsOut[ownerIndex].length;
if (ownerIndexTokens == 0) {
continue;
}
// The group's owner is taken from its first token and every other token in the group
// must agree, so the accumulated proceeds below can be paid out in one deposit
owner = _listings[collection][params.tokenIdsOut[ownerIndex][0]].owner;
for (uint i; i < ownerIndexTokens; ++i) {
uint tokenId = params.tokenIdsOut[ownerIndex][i];
if (i != 0 && _listings[collection][tokenId].owner != owner) {
revert InvalidOwner();
}
_fillListing(collection, address(_collectionToken), tokenId, params.recipient);
}
// The premium above floor belongs to the listing owner; the floor portion is burned
ownerReceives = _tload(FILL_PRICE) - (ownerIndexTokens * FLOOR_VALUE);
if (ownerReceives != 0) {
_deposit(owner, address(_collectionToken), ownerReceives);
totalPrice += ownerReceives;
}
refundAmount = _tload(FILL_REFUND);
if (refundAmount != 0) {
_deposit(owner, address(_collectionToken), refundAmount);
assembly { tstore(FILL_REFUND, 0) }
}
// Cleared per group, so the next owner starts from zero
assembly { tstore(FILL_PRICE, 0) }
totalBurn_ += ownerIndexTokens;
}
// The fill fee comes out of the sellers' prepaid tax already held by this contract and is
// never debited from the buyer, so it stays outside the `maxSpend` ceiling below
uint fillFee = _tload(FILL_FEE);
uint floorBurn = totalBurn_ * FLOOR_VALUE;
// Buyer-side cost only: the premium routed to owners plus the floor burned from the
// caller. Guards against an owner front-running with `modifyListings` to raise the price
// between simulation and execution. Zero opts out.
uint buyerSpend = totalPrice + floorBurn;
if (params.maxSpend != 0 && buyerSpend > params.maxSpend) {
revert FillCostExceedsMaxSpend(buyerSpend, params.maxSpend);
}
// Funds the `_deposit` calls already made during the fill loop
SafeTransferLib.safeTransferFrom(address(_collectionToken), msg.sender, address(this), totalPrice);
// Burned straight from the caller's wallet, so no overpayment ever lands here to return
_collectionToken.burnFrom(msg.sender, floorBurn);
if (fillFee != 0) {
_depositCollectionFees(collection, _collectionToken, fillFee);
assembly { tstore(FILL_FEE, 0) }
}
emit ListingsFilled(collection, params.tokenIdsOut, msg.sender);
}
/**
* Buys out an existing DUTCH or LIQUID listing, or a floor item, and replaces it with the
* caller's own listing against the same tokenId.
*
* The caller receives no base amount. They pay the incumbent owner only the premium above
* floor — relisting a 1.2 listing costs 0.2 — the incumbent's prepaid tax is settled, and the
* caller then prepays tax on their own listing at whatever type its parameters imply.
*
* @param params The replacement listing, whose `tokenIds` must hold exactly one entry; a
* `maxPrice` ceiling on the incumbent's price that zero opts out of; and whether to pay the
* new listing's tax from the caller's escrow balance
*/
function relist(RelistParams calldata params) public nonReentrant lockerNotPaused {
CreateListing calldata _listing = params.listing;
// Only one tokenId is relisted, so reject multi-token payloads rather than silently
// discarding `tokenIds[1..]`
if (_listing.tokenIds.length != 1) revert RelistAcceptsSingleTokenOnly();
address _collection = _listing.collection;
uint _tokenId = _listing.tokenIds[0];
Listing memory oldListing = _listings[_collection][_tokenId];
// Buying out one's own listing would round-trip the premium and reset the tax window free
if (oldListing.owner == msg.sender) revert CallerIsAlreadyOwner();
// Stamp `created` to the current block, as `createListings` does. A caller-supplied future
// `created` would entomb the NFT: `getListingPrice` short-circuits on it, the
// `block.timestamp - created` inside `_resolveListingTax` underflows, and the {Locker}
// refuses to release a token that is still a listing — all while its backing circulates.
Listing memory listing = _listing.listing;
listing.created = uint40(block.timestamp);
(bool isAvailable, uint listingPrice) = getListingPrice(_collection, _tokenId);
if (!isAvailable) revert ListingNotAvailable();
// Ceiling on the incumbent's price, which settles at the price read in this block:
// without it the incumbent front-runs the relist with `modifyListings`, raises
// `floorMultiple` to the collection's `maxFloorMultiple` and pockets the difference. Zero
// opts out, as with {FillListingsParams.maxSpend}. The `listingPrice > FLOOR_VALUE` term
// skips the cases where the incumbent is paid nothing at all — a floor item, or a dutch
// listing already decayed to floor; front-running only moves the price up, so skipping
// them cannot be used to slip past the guard.
if (params.maxPrice != 0 && listingPrice > FLOOR_VALUE && listingPrice > params.maxPrice) {
revert RelistPriceExceedsMax(listingPrice, params.maxPrice);
}
// Settle the incumbent's window; `true` moves the tokens here rather than batching them
(uint _fees,) = _resolveListingTax(oldListing, _collection, true);
if (_fees != 0) {
emit ListingFeeCaptured(_collection, _tokenId, _fees);
}
ICollectionToken collectionToken = locker.collectionToken(_collection);
// Pay the incumbent the premium above floor; a floor item has no premium and no incumbent
uint listingFloorPrice = FLOOR_VALUE;
if (listingPrice > listingFloorPrice) {
unchecked {
SafeTransferLib.safeTransferFrom(address(collectionToken), msg.sender, oldListing.owner, listingPrice - listingFloorPrice);
}
}
// Validated against the normalised `created` above
_validateCreateListing(_collection, listing);
// Relisting a floor item creates a listing where none existed, so the counter has to grow
// or the matching decrement in `cancelListings` and `_fillListing` would underflow.
// Relisting over a live listing is a straight replacement and leaves the count alone.
if (oldListing.owner == address(0)) {
listingCount[_collection] += 1;
}
_listings[_collection][_tokenId] = listing;
// Held to the same per-token ceiling `createListings` enforces, so the new owner can
// still afford to cancel
uint listingTax = getListingTaxRequired(listing, _collection);
_assertTaxWithinFloorValue(listingTax);
payTaxWithEscrow(address(collectionToken), listingTax, params.payTaxWithEscrow);
emit ListingRelisted(_collection, _tokenId, listing);
}
/**
* Prices the prepaid tax for a listing through the collection's effective {ITaxCalculator}.
*
* @param _listing The listing shape to price; only `floorMultiple` and `duration` are read
* @param _collection The ERC721 collection whose effective calculator prices it
*
* @return taxRequired_ The prepaid tax for one token, denominated in the collection token
*/
function getListingTaxRequired(Listing memory _listing, address _collection) public view returns (uint taxRequired_) {
taxRequired_ = taxCalculator(_collection).calculateTax(_collection, _listing.floorMultiple, _listing.duration);
}
/**
* Holds a single listing's prepaid tax to {FLOOR_VALUE}.
*
* @dev `createListings` enforces this implicitly, reverting when the tax exceeds the
* `n * FLOOR_VALUE` it just minted. `modifyListings` and `relist` mint nothing, so without
* this they could move a listing past the ceiling and make the `(FLOOR_VALUE * n) - refund`
* in `cancelListings` underflow, leaving the owner unable to exit their own listing.
*
* @param _taxRequired The prepaid tax for a single listing, not a batch total
*/
function _assertTaxWithinFloorValue(uint _taxRequired) private pure {
if (_taxRequired > FLOOR_VALUE) revert ListingTaxExceedsFloorValue(_taxRequired, FLOOR_VALUE);
}
/**
* Collects tax from the caller, drawing on their escrow balance first when
* `_payTaxWithEscrow` is set and pulling only the remaining shortfall as an external transfer.
*
* @param _token The ERC20 to collect, in practice always the collection token
* @param _taxRequired The amount to collect; zero returns without touching either balance
* @param _payTaxWithEscrow Whether to draw on the caller's escrow balance before transferring
*/
function payTaxWithEscrow(address _token, uint _taxRequired, bool _payTaxWithEscrow) private {
if (_taxRequired == 0) {
return;
}
if (_payTaxWithEscrow) {
// Escrow covers at most the full charge, so a larger balance is only partly drawn
uint currentBalance = balances[msg.sender][_token];
uint amountPayingFromEscrow = (currentBalance > _taxRequired) ? _taxRequired : currentBalance;
if (amountPayingFromEscrow > 0) {
unchecked {
_taxRequired -= amountPayingFromEscrow;
balances[msg.sender][_token] = currentBalance - amountPayingFromEscrow;
}
}
}
if (_taxRequired != 0) {
SafeTransferLib.safeTransferFrom(_token, msg.sender, address(this), _taxRequired);
}
}
/**
* Splits a listing fee between the protocol and the pool's LPs, sending the protocol share to
* {INFTXV4Hook.ammBeneficiary} and donating the remainder to the pool. Every fee-bearing path
* routes through here so the four call sites cannot drift apart.
*
* @dev The protocol takes `ammFee / (ammFee + lpFee)`, matching the swap-fee split the hook
* applies in `_afterSwap`. A zero `ammFee` or an unset beneficiary sends the whole fee to LPs.
*
* @dev V4 sorts pool currencies low-to-high by address, so the collection token can land on
* either side. {INFTXV4Hook.depositFees} takes amounts in `(currency0, currency1)` order, so
* the orientation is resolved here against the active `nativeToken()` rather than assumed.
*
* @param _collection The ERC721 collection the fee was captured against
* @param _collectionToken The collection's ERC20, already resolved by the caller
* @param _fees The fee amount, denominated in the collection token
*/
function _depositCollectionFees(address _collection, ICollectionToken _collectionToken, uint _fees) private {
if (_fees == 0) return;
INFTXV4Hook impl = locker.implementation();
uint24 ammFee = impl.ammFee();
address ammBeneficiary = impl.ammBeneficiary();
if (ammFee != 0 && ammBeneficiary != address(0)) {
// `ammFee != 0` guarantees a non-zero denominator.
uint protocolShare = (_fees * ammFee) / (uint(ammFee) + impl.getCollectionFee(_collection));
// Rounding can leave the protocol nothing; the full `_fees` then falls through to LPs
if (protocolShare != 0) {
unchecked {
_fees -= protocolShare;
}
SafeTransferLib.safeTransfer(address(_collectionToken), ammBeneficiary, protocolShare);
emit ListingFeeProtocolCaptured(_collection, ammBeneficiary, protocolShare);
// The protocol absorbs the whole fee only when the LP fee is zero
if (_fees == 0) {
return;
}
}
}
_collectionToken.approve(address(impl), _fees);
// The collection token is `currency0` when the native token's address sorts above it
bool collectionIsCurrency0 = impl.nativeToken() > address(_collectionToken);
impl.depositFees(_collection, collectionIsCurrency0 ? _fees : 0, collectionIsCurrency0 ? 0 : _fees);
}
/**
* External shim over {NFTTransferLib.ownerOf}.
*
* @dev Exists because Solidity's `try`/`catch` only applies to an external call and the
* library helper is `internal`. It carries no authority and writes nothing, so exposing it is
* free. Routing through {NFTTransferLib} keeps the pre-standard dispatch in one place —
* CryptoPunks resolves via `punkIndexToAddress` rather than an absent ERC721 `ownerOf`.
*
* @dev The full external frame is the point, not an accident of the language rule: it is the
* only form that brings every way an ownership read can fail inside a frame the caller can
* catch — a reverting `ownerOf`, a codeless collection (the ABI decoder reverts on the empty
* returndata), and a dirty return. A `try` written inline against `IERC721` would leave the
* last two reverting in the caller's own frame, uncatchable, taking the whole batch with them.
*
* @dev No `catch` contains a callee that burns the gas forwarded to it; see {NFTTransferLib}.
*
* @param _collection The collection to query; CryptoPunks is dispatched through
* `punkIndexToAddress` by {NFTTransferLib} rather than `ownerOf`
* @param _tokenId The token ID to resolve the owner of
*
* @return owner_ Whatever the collection reports as the current owner; reverts rather than
* returning zero when the collection has no code, reverts itself, or returns garbage
*/
function nftOwnerOf(address _collection, uint _tokenId) external view returns (address owner_) {
owner_ = NFTTransferLib.ownerOf(_collection, _tokenId);
}
/**
* Whether the {Locker} currently holds the NFT backing a listing.
*
* @dev Any failure to resolve an owner — burned token, upgraded collection, no contract at
* all — is reported as `false`. For {getListingPrice} that is the right answer: a token whose
* ownership cannot be established is exactly as undeliverable as one owned by somebody else.
*
* @dev The collapse is lossy where {closeStaleListing} uses it. "The token is gone" and "this
* collection declined to answer" both arrive as `false` and only the first is unrecoverable.
* The collection is the sole source of truth on its own ownership, so nothing here can tell
* them apart; {closeStaleListing} bounds the damage on the consequence side instead.
*
* @param _collection The ERC721 collection backing the listing
* @param _tokenId The token ID to check custody of
*
* @return held_ True only if the ownership read succeeded and named the {Locker}
*/
function _lockerHoldsToken(address _collection, uint _tokenId) private view returns (bool held_) {
try this.nftOwnerOf(_collection, _tokenId) returns (address owner) {
held_ = owner == address(locker);
} catch {
held_ = false;
}
}
/**
* Determines the price and availability of a listing.
*
* @param _collection The ERC721 collection the token belongs to
* @param _tokenId The token ID to price, which need not carry a listing row
*
* @return isAvailable_ Whether the token can be bought right now
* @return price_ The price in collection token, after any dutch decay that applies
*/
function getListingPrice(address _collection, uint _tokenId) public view returns (bool isAvailable_, uint price_) {
// Not held by the {Locker} means not deliverable. The read is fallible — see
// {_lockerHoldsToken} — and an unresolvable owner reads as unavailable, not as a revert.
if (!_lockerHoldsToken(_collection, _tokenId)) {
return (isAvailable_, price_);
}
Listing memory listing = _listings[_collection][_tokenId];
// One NFT is worth exactly one collection token at the floor
price_ = FLOOR_VALUE;
// No listing row means a floor item, which sells at exactly the floor
if (listing.owner == address(0)) {
return (true, price_);
}
// The undecayed ask; `floorMultiple` is in hundredths, so 100 is the floor itself
uint totalPrice = (price_ * uint(listing.floorMultiple)) / MIN_FLOOR_MULTIPLE;
// A future-dated listing is not sellable, and the elapsed-time maths below would underflow
if (listing.created > block.timestamp) {
return (isAvailable_, totalPrice);
}
// Resolved once: classifies the dutch window and scales the trailing liquid-dutch decay
ListingConfig memory config = listingConfig(_collection);
if (listing.duration >= config.minDutchDuration && listing.duration <= config.maxDutchDuration) {
// Past its window a dutch listing has fully decayed and sits at the floor
if (block.timestamp > listing.created + listing.duration) {
return (true, price_);
}
// Only the premium above floor decays, linearly across `duration`
uint multiple = totalPrice - price_;
uint discount = (multiple * (block.timestamp - listing.created)) / listing.duration;
if (discount > multiple) {
return (true, price_);
}
// `discount <= multiple <= totalPrice` was just established
unchecked {
return (true, totalPrice - discount);
}
}
// A liquid listing past its window decays from that expiry over `liquidDutchDuration`
uint dutchesAt = listing.created + listing.duration;
if (dutchesAt < block.timestamp) {
// Only the premium above floor decays, linearly across the liquid-dutch window
uint multiple = totalPrice - price_;
uint discount = (multiple * (block.timestamp - dutchesAt)) / config.liquidDutchDuration;
if (discount > multiple) {
return (true, price_);
}
// `discount <= multiple <= totalPrice` was just established
unchecked {
return (true, totalPrice - discount);
}
}
// A live liquid listing sells at its undecayed ask
return (true, totalPrice);
}
/**
* Settles a listing's prepaid tax: the elapsed portion becomes fees for the pool and the
* protocol, the unelapsed remainder is owed back to the listing owner.
*
* @param _listing The listing being settled; a floor item, with a zero `owner`, settles nothing
* @param _collection The ERC721 collection the listing belongs to
* @param _action Whether to move the tokens here; when false the caller batches the returned
* figures across a loop and settles them itself
*
* @return fees_ The elapsed portion, destined for {_depositCollectionFees}
* @return refund_ The unelapsed portion, owed to the listing owner's escrow
*/
function _resolveListingTax(Listing memory _listing, address _collection, bool _action) private returns (uint fees_, uint refund_) {
// A floor item holds no prepaid tax
if (_listing.owner == address(0)) {
return (fees_, refund_);
}
uint taxPaid = getListingTaxRequired(_listing, _collection);
// Clamped to the per-token ceiling every write path enforces. This figure is recomputed
// through whichever {ITaxCalculator} is registered right now, not read back from what was
// collected, and both calculator setters take effect immediately for open listings.
// Repointing a collection at a calculator that prices higher would inflate `refund_` past
// the `(FLOOR_VALUE * n) - refund` burn budget in `cancelListings` and lock owners out of
// their own exit. A no-op unless a calculator changes under an open listing.
if (taxPaid > FLOOR_VALUE) {
taxPaid = FLOOR_VALUE;
}
if (taxPaid == 0) {
return (fees_, refund_);
}
// An expired listing refunds nothing, so its whole prepayment books as fees below
if (block.timestamp < _listing.created + _listing.duration) {
refund_ = (_listing.duration - (block.timestamp - _listing.created)) * taxPaid / _listing.duration;
}
unchecked {
fees_ = (taxPaid > refund_) ? taxPaid - refund_ : 0;
}
if (_action) {
ICollectionToken collectionToken = locker.collectionToken(_collection);
_depositCollectionFees(_collection, collectionToken, fees_);
if (refund_ != 0) {
_deposit(_listing.owner, address(collectionToken), refund_);
}
}
}
/**
* Classifies a listing from `duration` and `created` against the collection's resolved
* {ListingConfig}, so per-collection overrides to the dutch window apply here too.
*
* @param _collection The ERC721 collection whose config supplies the dutch window
* @param _listing The listing to classify; a zero `owner` is the floor-item sentinel
*
* @return `NONE` for a floor item, `DUTCH` for one created inside the dutch window or a
* liquid listing past its expiry, `LIQUID` otherwise
*/
function getListingType(address _collection, Listing memory _listing) public view returns (Enums.ListingType) {
// A zero owner means there is no listing row at all: a plain floor item
if (_listing.owner == address(0)) {
return Enums.ListingType.NONE;
}
ListingConfig memory config = listingConfig(_collection);
// Created inside the dutch window, or a liquid listing that has run out and reclassifies
if (
(_listing.duration >= config.minDutchDuration && _listing.duration <= config.maxDutchDuration)
|| _listing.created + _listing.duration < block.timestamp
) {
return Enums.ListingType.DUTCH;
}
return Enums.ListingType.LIQUID;
}
/**
* Reads a transient storage slot.
*
* @param location The transient slot key to read, one of `FILL_FEE`, `FILL_PRICE` or
* `FILL_REFUND`
*
* @return value The word held in that slot, zero once the slot has been cleared
*/
function _tload(bytes32 location) private view returns (uint value) {
assembly {
value := tload(location)
}
}
/**
* Helper modifier to prevent the attached function from being called if the {Locker} is paused.
*/
modifier lockerNotPaused() {
if (locker.paused()) revert Paused();
_;
}
}
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.
/// - For ERC20s, this implementation won't check that a token has code,
/// responsibility is delegated to the caller.
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 Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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 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;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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)`.
// Perform the transfer, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
)
) {
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 := and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
)
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.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
)
) {
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.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
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.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
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)`.
// Perform the approval, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
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.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
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.
if iszero(
and(
or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
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 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), 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), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `1` 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(call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00)) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
}
lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/v4-hooks-public/lib/v4-core/src/interfaces/IHooks.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
lib/v4-hooks-public/lib/v4-core/src/interfaces/external/IERC20Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
/// @notice Returns an account's balance in the token
/// @param account The account for which to look up the number of tokens it has, i.e. its balance
/// @return The number of tokens held by the account
function balanceOf(address account) external view returns (uint256);
/// @notice Transfers the amount of token from the `msg.sender` to the recipient
/// @param recipient The account that will receive the amount transferred
/// @param amount The number of tokens to send from the sender to the recipient
/// @return Returns true for a successful transfer, false for an unsuccessful transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Returns the current allowance given to a spender by an owner
/// @param owner The account of the token owner
/// @param spender The account of the token spender
/// @return The current allowance granted by `owner` to `spender`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
/// @param spender The account which will be allowed to spend a given amount of the owners tokens
/// @param amount The amount of tokens allowed to be used by `spender`
/// @return Returns true for a successful approval, false for unsuccessful
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
/// @param sender The account from which the transfer will be initiated
/// @param recipient The recipient of the transfer
/// @param amount The amount of the transfer
/// @return Returns true for a successful transfer, false for unsuccessful
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
/// @param from The account from which the tokens were sent, i.e. the balance decreased
/// @param to The account to which the tokens were sent, i.e. the balance increased
/// @param value The amount of tokens that were transferred
event Transfer(address indexed from, address indexed to, uint256 value);
/// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
/// @param owner The account that approved spending of its tokens
/// @param spender The account for which the spending allowance was modified
/// @param value The new allowance from the owner to the spender
event Approval(address indexed owner, address indexed spender, uint256 value);
}
lib/v4-hooks-public/lib/v4-core/src/libraries/CustomRevert.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
lib/v4-hooks-public/lib/v4-core/src/libraries/SafeCast.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
lib/v4-hooks-public/lib/v4-core/src/types/BalanceDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
lib/v4-hooks-public/lib/v4-core/src/types/BeforeSwapDelta.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
lib/v4-hooks-public/lib/v4-core/src/types/Currency.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success := and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
lib/v4-hooks-public/lib/v4-core/src/types/PoolId.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}
lib/v4-hooks-public/lib/v4-core/src/types/PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}
lib/v4-hooks-public/lib/v4-core/src/types/PoolOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
src/contracts/TokenEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {SafeTransferLib} from 'solady/utils/SafeTransferLib.sol';
import {ITokenEscrow} from 'nftx-interfaces/ITokenEscrow.sol';
/**
* Holds tokens allocated to a user until they choose to claim them, so the allocating call
* only writes a balance rather than paying for a transfer to each recipient.
*/
abstract contract TokenEscrow is ITokenEscrow {
/// Sentinel `_token` value routing a transfer to the chain's native token instead of an ERC20
address public constant NATIVE_TOKEN = address(0);
/// Escrowed balance held for each recipient, per token
mapping(address _recipient => mapping(address _token => uint _amount)) public balances;
/**
* Credits `_recipient` with an amount of a token, claimable through {withdraw}.
*
* @dev This is accounting only. The inheriting contract must already hold the funds being
* credited, otherwise the recipient's withdrawal will fail at transfer time.
*
* @param _recipient The recipient of the transferred token
* @param _token The token to be transferred (`NATIVE_TOKEN` for ETH)
* @param _amount The amount of the token to be transferred
*/
function _deposit(address _recipient, address _token, uint _amount) internal {
balances[_recipient][_token] += _amount;
emit Deposit(_recipient, _token, _amount, msg.sender);
}
/**
* Allows a user to withdraw from their escrow position. Funds are always
* debited from `msg.sender` (so the source cannot be widened) but may be
* sent to any non-zero recipient.
*
* @param _recipient The address to receive the withdrawn token / ETH
* @param _token The token to be transferred (`NATIVE_TOKEN` for ETH)
* @param _amount The amount of the token to be transferred
*/
function withdraw(address _recipient, address _token, uint _amount) public {
if (_amount == 0) revert CannotWithdrawZeroAmount();
if (_recipient == address(0)) revert RecipientIsZeroAddress();
uint available = balances[msg.sender][_token];
if (available < _amount) revert InsufficientBalanceAvailable();
// Guarded by the sufficiency check above, so the subtraction cannot underflow
unchecked {
balances[msg.sender][_token] = available - _amount;
}
if (_token == NATIVE_TOKEN) {
SafeTransferLib.safeTransferETH(_recipient, _amount);
}
// No registry check: any address other than the sentinel is assumed to be an ERC20
else {
SafeTransferLib.safeTransfer(_token, _recipient, _amount);
}
emit Withdrawal(msg.sender, _recipient, _token, _amount);
}
}
src/contracts/libraries/NFTTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {ICryptoKitties} from 'nftx-interfaces/ICryptoKitties.sol';
import {ICryptoPunksMarket} from 'nftx-interfaces/ICryptoPunksMarket.sol';
/**
* NFTTransferLib gives uniform transfer, ownership and approval helpers across standard ERC721,
* native CryptoPunks and CryptoKitties. Consumers add `using NFTTransferLib for address;` and then
* treat a collection address the same way regardless of the underlying flavor.
*
* Dispatch is a hard-coded address allowlist against the canonical Ethereum mainnet deployments,
* so the legacy branches are unreachable on chains where those contracts do not exist.
*/
library NFTTransferLib {
/// Canonical CryptoPunks marketplace deployment on Ethereum mainnet.
address internal constant PUNKS = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
/// Canonical CryptoKitties Core deployment on Ethereum mainnet.
address internal constant KITTIES = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
/// ERC165 interface ID for ERC721 (`type(IERC721).interfaceId`).
bytes4 internal constant ERC721_INTERFACE_ID = 0x80ac58cd;
enum Flavor {
ERC721,
PUNKS,
KITTIES
}
/// Thrown when a punk pull is attempted but the seller offered the punk to a different address
/// than the contract attempting to pull it.
error PunkNotOfferedToOperator(address collection, uint tokenId, address expectedOperator, address actualOperator);
/// Thrown when a punk pull is attempted against a punk that is not currently offered for sale.
error PunkNotOffered(address collection, uint tokenId);
/// Thrown when the open offer was made by somebody other than the account the pull is being
/// charged to. Without this the offer is a bearer instrument: anyone could consume an offer
/// made to this contract and direct the proceeds to themselves.
error PunkNotOfferedBySender(address collection, uint tokenId, address expectedSeller, address actualSeller);
/// Thrown when a punk pull is attempted against an offer with a non-zero price. Only
/// zero-priced offers are supported.
error PunkRequiresZeroPriceOffer(address collection, uint tokenId, uint minValue);
/// Thrown when `isShutdownSupported` is asserted against a collection whose transfer flow does
/// not support the shutdown path, currently CryptoPunks and CryptoKitties.
error NonStandardCollection(address collection);
/// Thrown when a push is directed at the zero address. `CryptoPunksMarket` has no zero-check
/// of its own, so without this the asset is destroyed rather than the call reverting.
error PushToZeroAddress(address collection, uint tokenId);
/// Thrown when a pull names this contract as the source. Such a pull satisfies both of {pull}'s
/// ownership assertions without anything having moved, which for {Locker} is an unbacked mint.
/// Defence-in-depth: every call site passes `msg.sender`, and `requestAirdrop` rejects
/// `_contract == address(this)` before reaching here.
error SelfPull(address collection);
/// Thrown when a collection will not name the owner of a token — it reverted, it has no code,
/// or it answered with something that is not an address. Fatal rather than collapsed to
/// `false`, because the caller is about to mint against the answer.
error OwnershipUnverifiable(address collection, uint tokenId);
/// Thrown when the account a pull is being charged to does not own the token at the point the
/// pull starts.
error NotOwnedBySender(address collection, uint tokenId, address expectedOwner, address actualOwner);
/// Thrown when a pull returned without reverting but this contract does not hold the token
/// afterwards — the collection's `transferFrom` was a silent no-op.
error TransferFailed(address collection, uint tokenId, address expectedOwner, address actualOwner);
/**
* Returns the transfer-flow flavor for a collection. The decision is purely an address
* allowlist, so any contract that is not the canonical Punks or Kitties deployment is treated
* as a standard ERC721.
*
* @param _contract The collection being classified
*
* @return The branch to dispatch on: `Flavor.PUNKS`, `Flavor.KITTIES` or `Flavor.ERC721`
*/
function flavor(address _contract) internal pure returns (Flavor) {
if (_contract == PUNKS) return Flavor.PUNKS;
if (_contract == KITTIES) return Flavor.KITTIES;
return Flavor.ERC721;
}
/**
* Returns true when a collection can be registered with the {Locker}.
*
* @dev The code check sits above the flavor dispatch because the Punks and Kitties addresses
* are empty accounts on every chain but Ethereum mainnet. Registering a collection against
* nothing is permanent: the clone is deployed, `CollectionAlreadyExists` blocks re-registration
* and {CollectionShutdown} cannot clear it because `isShutdownSupported` rejects both flavors.
*
* @dev That check is also what makes a codeless address return `false` rather than revert —
* `try`/`catch` does not intercept the `extcodesize` guard solc emits ahead of an external call
* with a return value. The `catch` covers contracts that have code but do not implement ERC165.
*
* @param _contract The collection being considered for registration
*
* @return True when `_contract` has code and either is a legacy flavor or answers
* `ERC721_INTERFACE_ID` through ERC165; false for a codeless or non-ERC165 account
*/
function isLockerCompatible(address _contract) internal view returns (bool) {
if (_contract.code.length == 0) return false;
Flavor _flavor = flavor(_contract);
if (_flavor != Flavor.ERC721) return true;
try IERC165(_contract).supportsInterface(ERC721_INTERFACE_ID) returns (bool ok) {
return ok;
} catch {
return false;
}
}
/**
* Returns true when a collection's transfer/approval flow is compatible with the
* Sudoswap-backed shutdown path.
*
* @param _contract The collection being checked
*
* @return True only for standard ERC721; CryptoPunks and CryptoKitties are not supported
*/
function isShutdownSupported(address _contract) internal pure returns (bool) {
return flavor(_contract) == Flavor.ERC721;
}
/**
* Pulls a single NFT from `_from` into the calling contract.
*
* @dev ERC721 and Kitties need `_from` to have pre-approved this contract; Punks
* need a zero-price offer made exclusively to it, settled via `buyPunk{value: 0}`.
*
* @dev Ownership is asserted before and after the transfer, so callers minting
* against the result cannot be paid by a `transferFrom` that silently does nothing
* — an upgradeable ERC721 repointed at a no-op, or a self-destructed collection
* (`transferFrom` has no return value, so solc emits no `extcodesize` guard). The
* assertions read the collection's own `ownerOf`, so a collection written to lie
* defeats them; registration is the only control there. Costs ~3.3k gas per token.
*
* @param _contract The collection the token is being pulled from
* @param _from The account being charged for the token
* @param _tokenId The token being pulled
*/
function pull(address _contract, address _from, uint _tokenId) internal {
if (_from == address(this)) revert SelfPull(_contract);
Flavor _flavor = flavor(_contract);
if (_flavor == Flavor.PUNKS) {
_pullPunk(_contract, _from, _tokenId);
}
// ERC721 and Kitties both settle through the standard `transferFrom` entrypoint
else {
_requirePullable(_contract, _from, _tokenId, _flavor);
IERC721(_contract).transferFrom(_from, address(this), _tokenId);
}
_requireReceived(_contract, _tokenId, _flavor);
}
/**
* Sends a single NFT held by the calling contract to `_to`.
*
* @dev The zero-address guard is the library's, not the collections'. OpenZeppelin's ERC721
* reverts with `ERC721InvalidReceiver` and KittyCore's `transfer` requires a non-zero
* recipient, but `CryptoPunksMarket.transferPunk` has no check at all — it writes
* `punkIndexToAddress[idx] = to` and the punk is destroyed with no way back.
*
* @param _contract The collection holding the token
* @param _to The recipient, which must not be the zero address
* @param _tokenId The token being sent
*/
function push(address _contract, address _to, uint _tokenId) internal {
if (_to == address(0)) revert PushToZeroAddress(_contract, _tokenId);
Flavor _flavor = flavor(_contract);
if (_flavor == Flavor.PUNKS) {
ICryptoPunksMarket(_contract).transferPunk(_to, _tokenId);
}
// KittyCore's `transferFrom` requires the per-token operator rather than the owner, so
// owner-initiated sends route through `transfer`, which only checks ownership
else if (_flavor == Flavor.KITTIES) {
ICryptoKitties(_contract).transfer(_to, _tokenId);
}
// This contract is the owner here, so no approval is involved
else {
IERC721(_contract).transferFrom(address(this), _to, _tokenId);
}
}
/**
* Returns the current owner of a token.
*
* @dev CryptoPunks exposes ownership via the `punkIndexToAddress` mapping rather than the
* ERC721 {ownerOf} entrypoint.
*
* @param _contract The collection to query
* @param _tokenId The token to look up
*
* @return The account the collection names as holding `_tokenId`; reverts if it will not answer
*/
function ownerOf(address _contract, uint _tokenId) internal view returns (address) {
Flavor _flavor = flavor(_contract);
if (_flavor == Flavor.PUNKS) {
return ICryptoPunksMarket(_contract).punkIndexToAddress(_tokenId);
}
return IERC721(_contract).ownerOf(_tokenId);
}
/**
* Non-reverting variant of {ownerOf}, so a caller can tell a collection that will not answer
* from one that names an owner. Solidity's `try` wraps only external calls and {ownerOf} is
* `internal`, hence the raw `staticcall` rather than an external `view` shim to hop through.
*
* @dev Anything other than a named address gives `ok_ == false`: a revert, an account with no
* code (a `staticcall` to one succeeds with empty returndata), a short return, or a word with
* dirty upper bits. A longer return is accepted and its first word decoded, matching `ownerOf`.
*
* @dev EIP-150 forwards 63/64 of the remaining gas to the callee, so a collection that burns
* all of it leaves this frame with 1/64 of what it had; the caller has to quote enough gas.
*
* @param _contract The collection to probe, which may have no code at all
* @param _tokenId The token to look up
*
* @return ok_ True only if the collection returned a well-formed address
* @return owner_ The address returned, or the zero address when `ok_` is false
*/
function tryOwnerOf(address _contract, uint _tokenId) internal view returns (bool ok_, address owner_) {
return _tryOwnerOf(_contract, _tokenId, flavor(_contract));
}
/**
* {tryOwnerOf} with the flavor supplied by the caller.
*
* @dev The deposit path resolves the flavor once and then makes `2N` ownership probes against
* it, so threading the resolved value through saves recomputing {flavor} inside each one.
*
* @param _contract The collection to probe, which may have no code at all
* @param _tokenId The token to look up
* @param _flavor The already-resolved flavor of `_contract`
*
* @return ok_ True only if the collection returned a well-formed address
* @return owner_ The address returned, or the zero address when `ok_` is false
*/
function _tryOwnerOf(address _contract, uint _tokenId, Flavor _flavor) private view returns (bool ok_, address owner_) {
// Punks exposes ownership through a mapping getter rather than {ownerOf}
bytes memory payload = _flavor == Flavor.PUNKS
? abi.encodeCall(ICryptoPunksMarket.punkIndexToAddress, (_tokenId))
: abi.encodeCall(IERC721.ownerOf, (_tokenId));
(bool success, bytes memory data) = _contract.staticcall(payload);
// A `staticcall` into an empty account reports success with no data, so the length check is
// what rejects a collection that is not there. Over-long returndata is accepted, hence
// `< 32` rather than `!= 32`.
if (!success || data.length < 32) return (false, address(0));
// Decode as a word rather than an address: `abi.decode(_, (address))` reverts on dirty
// upper bits, which would defeat the point of a non-reverting probe
uint word;
assembly ('memory-safe') {
word := mload(add(data, 0x20))
}
if (word > type(uint160).max) return (false, address(0));
// The line above is the range check, so this cast cannot truncate
// forge-lint: disable-next-line(unsafe-typecast)
return (true, address(uint160(word)));
}
/**
* Asserts that `_from` is in a position to have a token pulled from it.
*
* @dev Without the pre-condition, a `transferFrom` that silently does nothing would let one
* real deposit be re-deposited forever, since the post-check passes on a token already held.
*
* @dev The punks branch skips it: {_pullPunk} asserts the offer's `seller` is `_from`, and
* `buyPunk` asserts `seller` is the current holder, which is this check by transitivity.
*
* @param _contract The collection the token is being pulled from
* @param _from The account the pull is being charged to
* @param _tokenId The token about to be pulled
* @param _flavor The already-resolved flavor of `_contract`
*/
function _requirePullable(address _contract, address _from, uint _tokenId, Flavor _flavor) private view {
(bool ok_, address owner_) = _tryOwnerOf(_contract, _tokenId, _flavor);
if (!ok_) revert OwnershipUnverifiable(_contract, _tokenId);
if (owner_ != _from) revert NotOwnedBySender(_contract, _tokenId, _from, owner_);
}
/**
* Asserts that this contract holds the token after a pull.
*
* @param _contract The collection the token was pulled from
* @param _tokenId The token that should now be held by this contract
* @param _flavor The already-resolved flavor of `_contract`
*/
function _requireReceived(address _contract, uint _tokenId, Flavor _flavor) private view {
(bool ok_, address owner_) = _tryOwnerOf(_contract, _tokenId, _flavor);
if (!ok_) revert OwnershipUnverifiable(_contract, _tokenId);
// A `transferFrom` that did not revert is not proof that the NFT arrived
if (owner_ != address(this)) revert TransferFailed(_contract, _tokenId, address(this), owner_);
}
/**
* Authorises `_operator` to pull a specific token from the calling contract.
*
* @dev Per-token on every flavor: ERC721 and Kitties each expose an `approve`, and Punks uses
* {ICryptoPunksMarket.offerPunkForSaleToAddress} at price zero.
*
* @param _contract The collection holding the token
* @param _operator The account being authorised to pull the token
* @param _tokenId The token the authorisation is scoped to
*/
function approveOperatorForToken(address _contract, address _operator, uint _tokenId) internal {
Flavor _flavor = flavor(_contract);
if (_flavor == Flavor.PUNKS) {
ICryptoPunksMarket(_contract).offerPunkForSaleToAddress(_tokenId, 0, _operator);
}
// Kitties predates ERC721 but takes the same `approve(operator, tokenId)` shape
else if (_flavor == Flavor.KITTIES) {
ICryptoKitties(_contract).approve(_operator, _tokenId);
}
// ERC721's `approve` is already scoped to the single token
else {
IERC721(_contract).approve(_operator, _tokenId);
}
}
/**
* Batch variant of {approveOperatorForToken}. Callers must pair it with
* {revokeOperatorApproval}.
*
* @dev The ERC721 branch grants `_operator` blanket authority over the whole collection rather
* than over `_tokenIds`, which is read for its length and by the legacy branches only. A single
* blanket grant is two storage writes whatever the batch size, where per-token approval writes
* a slot each, so the grant is deliberately wide and withdrawn explicitly afterwards.
*
* @param _contract The collection holding the tokens
* @param _operator The account being authorised to pull the tokens
* @param _tokenIds The tokens to authorise, an empty array being a no-op; the ERC721 branch
* reads only its length, the legacy branches approve every entry
*/
function approveOperatorForTokens(address _contract, address _operator, uint[] calldata _tokenIds) internal {
// Get the number of tokens to approve and return early if there are none
uint len = _tokenIds.length;
if (len == 0) return;
// Get the flavor of the collection
Flavor _flavor = flavor(_contract);
// Check if the collection is CryptoPunks
if (_flavor == Flavor.PUNKS) {
ICryptoPunksMarket _punks = ICryptoPunksMarket(_contract);
for (uint i; i < len; ++i) {
_punks.offerPunkForSaleToAddress(_tokenIds[i], 0, _operator);
}
}
// Neither legacy flavor has a blanket-approval entrypoint, so both loop per token
else if (_flavor == Flavor.KITTIES) {
ICryptoKitties _kitties = ICryptoKitties(_contract);
for (uint i; i < len; ++i) {
_kitties.approve(_operator, _tokenIds[i]);
}
}
// One blanket grant, skipped when it is already standing
else {
IERC721 _erc721 = IERC721(_contract);
if (!_erc721.isApprovedForAll(address(this), _operator)) {
_erc721.setApprovalForAll(_operator, true);
}
}
}
/**
* Withdraws an operator authorisation granted by {approveOperatorForTokens}.
*
* @dev Only the ERC721 branch has anything to withdraw. Punks and Kitties are authorised per
* token, the authorisation is consumed by the transfer, and neither could be cleared afterwards
* anyway: `punkNoLongerForSale` and `KittyCore.approve` require the caller to still own it.
*
* @dev Without this the blanket grant stands forever, leaving {Listings} and {NFTXZap} holding
* an unscoped approval to the {Locker} for every collection they have touched — which is why
* `Locker._validateAirdropTarget` denies the append-only {Listings} set. Revoking scopes the
* grant to the single call frame in which the caller invoked the {Locker}.
*
* @param _contract The collection the blanket approval was granted on
* @param _operator The account whose blanket approval is being withdrawn
*/
function revokeOperatorApproval(address _contract, address _operator) internal {
// Nothing to revoke on the legacy flavors
if (flavor(_contract) != Flavor.ERC721) return;
IERC721 _erc721 = IERC721(_contract);
// Only write if the approval is actually standing
if (_erc721.isApprovedForAll(address(this), _operator)) {
_erc721.setApprovalForAll(_operator, false);
}
}
/**
* Settles a single zero-priced CryptoPunks offer made by `_from` to this contract.
*
* @dev CryptoPunks has no `approve(operator)`, so a deposit is two transactions: the owner
* calls `offerPunkForSaleToAddress(id, 0, thisContract)`, then `buyPunk{value: 0}` settles it.
*
* @dev Binding the offer to `_from` stops it being a bearer instrument: anybody could otherwise
* consume it between the owner's two transactions and take the CollectionToken, or via
* `Locker.swap` a punk of their choosing. The ERC721 path gets this free from `transferFrom`.
*
* @param _contract The CryptoPunks market the offer was made on
* @param _from The account the pull is being charged to
* @param _tokenId The punk index being settled
*/
function _pullPunk(address _contract, address _from, uint _tokenId) private {
(bool isForSale,, address seller, uint minValue, address onlySellTo) = ICryptoPunksMarket(_contract).punksOfferedForSale(_tokenId);
// Revert with a clear reason rather than letting `buyPunk` fail opaquely
if (!isForSale) revert PunkNotOffered(_contract, _tokenId);
if (seller != _from) revert PunkNotOfferedBySender(_contract, _tokenId, _from, seller);
if (onlySellTo != address(this)) {
revert PunkNotOfferedToOperator(_contract, _tokenId, address(this), onlySellTo);
}
if (minValue != 0) revert PunkRequiresZeroPriceOffer(_contract, _tokenId, minValue);
ICryptoPunksMarket(_contract).buyPunk{value: 0}(_tokenId);
}
/**
* Batch variant of {pull}, carrying the same per-token ownership assertions.
*
* @dev Those assertions also reject a duplicate ID: the second copy fails {_requirePullable},
* because by then the token belongs to this contract rather than to `_from`. On the punks
* branch the duplicate is caught by {PunkNotOffered}, since `buyPunk` consumes the offer.
*
* @param _contract The collection the tokens are being pulled from
* @param _from The account being charged for the tokens
* @param _tokenIds The tokens being pulled, an empty array being a no-op; duplicate IDs revert
*/
function pullBatch(address _contract, address _from, uint[] calldata _tokenIds) internal {
// Checked before the empty-batch return so this and {pull} reject the same argument for the
// same reason, rather than one of them treating an empty self-pull as a no-op
if (_from == address(this)) revert SelfPull(_contract);
// Get the number of tokens to pull and return early if there are none
uint len = _tokenIds.length;
if (len == 0) return;
// Get the flavor of the collection
Flavor _flavor = flavor(_contract);
// Check if the collection is CryptoPunks
if (_flavor == Flavor.PUNKS) {
for (uint i; i < len; ++i) {
_pullPunk(_contract, _from, _tokenIds[i]);
_requireReceived(_contract, _tokenIds[i], _flavor);
}
}
// ERC721 and Kitties both settle through the standard `transferFrom` entrypoint
else {
IERC721 _erc721 = IERC721(_contract);
for (uint i; i < len; ++i) {
_requirePullable(_contract, _from, _tokenIds[i], _flavor);
_erc721.transferFrom(_from, address(this), _tokenIds[i]);
_requireReceived(_contract, _tokenIds[i], _flavor);
}
}
}
}
src/interfaces/Enums.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
interface Enums {
/**
* Defines the different types of claim types available.
*/
enum ClaimType {
ERC20,
ERC721,
ERC1155,
NATIVE
}
/**
* There will be four types of listings that are able to be created. These won't
* need to be stored against the actual {Listing} struct, but will need to be defined
* when creating a Listing to determine that validation placed against it.
*
* Dutch
* - expires at point of listing
* - floorMultiplier set at point of listing
*
* Liquid
* - Expires when duration runs out
* - floorMultiplier set at point of listing
*/
enum ListingType {
DUTCH,
LIQUID,
NONE
}
}
src/interfaces/ICollectionLaunchGate.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/**
* External, swappable authority that the {Locker} consults to decide who may
* launch a collection (create + initialize) and whether token-only single-sided
* liquidity launches are permitted.
*
* The decentralisation timeline is expressed by which concrete gate is wired
* into the {Locker}:
*
* - {WhiteGlove} — only the gate's `owner()` (our multisig) may launch.
* - {Public} — anyone may launch.
*
* Each gate fixes `singleSidedAllowed()` at deployment; the {Locker} reads it to
* decide whether a `_eth == 0` (token-only) launch is permitted. Progressing the
* timeline is a `setLaunchGate` swap to a differently-configured gate.
*
* The auth guards are declared non-`view` so a future gate can hold stateful
* policy without an interface break; the shipped gates implement them as `view`.
*/
interface ICollectionLaunchGate {
/// Reverts when the gate restricts launches and `caller` is not authorised
error LaunchRestricted(address caller);
/// Whether token-only single-sided liquidity launches are permitted through
/// this gate. Read by the {Locker} when a launch supplies zero native.
function singleSidedAllowed() external view returns (bool);
/// The ETH fee charged per collection creation while this gate is wired into
/// the {Locker}, in wei. The gate is the sole authority on creation pricing —
/// the {Locker} holds no fee of its own — so a multisig-only phase can launch
/// for free while a public phase charges.
function collectionCreationFee() external view returns (uint);
/// The address paid {collectionCreationFee} on each creation. Only consulted
/// when the fee is non-zero, so a free gate may leave it unset.
function collectionCreationFeeRecipient() external view returns (address);
/**
* Reverts unless `caller` may create `collection` through this gate.
*
* @param caller The user attempting the launch (the {Locker}'s `msg.sender`)
* @param collection The collection being created
*/
function assertCanCreateCollection(address caller, address collection) external;
/**
* Reverts unless `caller` may initialize `collection` through this gate.
*
* @param caller The user attempting the launch (the {Locker}'s `msg.sender`)
* @param collection The collection being initialized
*/
function assertCanInitializeCollection(address caller, address collection) external;
}
src/interfaces/ICollectionToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface ICollectionToken is IERC20 {
function initialize(string calldata name_, string calldata symbol_) external;
function mint(address _to, uint _amount) external;
function setMetadata(string calldata name_, string calldata symbol_) external;
function burn(uint value) external;
function burnFrom(address account, uint value) external;
}
src/interfaces/ICryptoKitties.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/**
* Minimal interface for the CryptoKitties Core contract deployed on Ethereum
* mainnet at 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d.
*
* CryptoKitties predates the final ERC721 standard. It exposes a
* {transferFrom}/{ownerOf} pair that matches the ERC721 signatures but does
* not expose {setApprovalForAll} or return true for
* `supportsInterface(0x80ac58cd)`. It also exposes an owner-only {transfer}
* helper which we prefer for "push" flows because Kitties' {transferFrom}
* requires the caller to be the per-token operator rather than the owner.
*/
interface ICryptoKitties {
function transferFrom(address from, address to, uint tokenId) external;
function transfer(address to, uint tokenId) external;
function approve(address to, uint tokenId) external;
function ownerOf(uint tokenId) external view returns (address);
}
src/interfaces/ICryptoPunksMarket.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/**
* Minimal interface for the CryptoPunks marketplace contract deployed on
* Ethereum mainnet at 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB.
*
* CryptoPunks predates ERC721 (and ERC165), so transfers happen via a
* marketplace baked into the contract: the seller "offers" the punk to a
* specific buyer at a chosen price, then the buyer calls {buyPunk}. To pull a
* punk into a contract without paying ETH, the seller offers it at a price of
* zero exclusively to that contract, and the contract finalises the move with
* `buyPunk{value: 0}(punkIndex)`.
*/
interface ICryptoPunksMarket {
function transferPunk(address to, uint punkIndex) external;
function buyPunk(uint punkIndex) external payable;
function offerPunkForSaleToAddress(uint punkIndex, uint minSalePriceInWei, address toAddress) external;
function punksOfferedForSale(uint punkIndex)
external
view
returns (bool isForSale, uint punkIndex_, address seller, uint minValue, address onlySellTo);
function punkIndexToAddress(uint punkIndex) external view returns (address);
}
src/interfaces/IListings.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Enums} from 'nftx-interfaces/Enums.sol';
import {ILocker} from 'nftx-interfaces/ILocker.sol';
import {ITaxCalculator} from 'nftx-interfaces/ITaxCalculator.sol';
interface IListings {
/// Error when zero address is provided for the locker
error LockerIsZeroAddress();
/// Error when zero address is provided for the default tax calculator
error TaxCalculatorIsZeroAddress();
/// Error when a {ListingConfig} fails the cross-field invariants enforced
/// by `setDefaultListingConfig` / `setCollectionListingConfig`
error InvalidListingConfig();
/// Error when insufficient tax is provided for a transaction
error InsufficientTax(uint _taxPaid, uint _taxRequired);
/// Reverts when a listing's prepaid tax would exceed the floor value of a
/// single token. `cancelListings` funds its burn as `(1 ether * n) - refund`,
/// so a prepayment above that ceiling makes the owner's exit impossible.
error ListingTaxExceedsFloorValue(uint _taxRequired, uint _maxTax);
/// Error when the listing's floor multiple doesn't match our expected value
error InvalidFloorMultiple(uint16 _floorMultiple, uint16 _expectedFloorMultiple);
/// Error when the token doesn't exist in the {Locker} contract
error LockerIsNotTokenHolder();
error CollectionNotInitialized();
error ListingOwnerIsZero();
error FloorMultipleMustBeAbove100(uint16 _floorMultiple);
error FloorMultipleExceedsMax(uint16 _floorMultiple, uint16 _maxFloorMultiple);
error ListingDurationBelowMin(uint32 _duration, uint32 _minListingDuration);
error ListingDurationExceedsMax(uint32 _duration, uint32 _maxListingDuration);
error InvalidListingType();
error CallerIsNotOwner(address _expectedCaller);
error NewOwnerIsZero();
error CannotCancelListingType();
error ListingNotAvailable();
error InvalidCollection();
error InvalidOwner();
error CallerIsAlreadyOwner();
error Paused();
/// Reverts when the realised fill total exceeds the buyer's `maxSpend`
error FillCostExceedsMaxSpend(uint _totalCost, uint _maxSpend);
/// Reverts when `relist` is invoked with a multi-tokenId payload (only
/// `tokenIds[0]` is processed by `relist`; pass exactly one)
error RelistAcceptsSingleTokenOnly();
/// Reverts when the incumbent listing's price exceeds the relister's `maxPrice`
error RelistPriceExceedsMax(uint _listingPrice, uint _maxPrice);
/// Reverts when `closeStaleListing` is called against a tokenId that has no
/// open listing — there is nothing to close and nothing to decrement
error ListingDoesNotExist(address _collection, uint _tokenId);
/// Reverts when `closeStaleListing` is called against a listing whose NFT is
/// still held by the {Locker}, i.e. a healthy listing
error ListingIsNotStale(address _collection, uint _tokenId);
/// Emitted when a new listing is created
event ListingsCreated(
address indexed _collection,
uint[] _tokenIds,
Listing _listing,
Enums.ListingType _listingType,
uint _tokensRequired,
uint _taxRequired,
address _sender
);
/// Emitted when a listing is relisted
event ListingRelisted(address indexed _collection, uint _tokenId, Listing _listing);
/// Emitted when a 1 - n listings are filled
event ListingsFilled(address indexed _collection, uint[][] _tokenIds, address _recipient);
/// Emitted when a listing is transferred to another owner
event ListingTransferred(address indexed _collection, uint _tokenId, address _owner, address _newOwner);
/// Emitted when a listing is cancelled by the owner
event ListingsCancelled(address indexed _collection, uint[] _tokenIds);
/// Emitted when a listing whose backing NFT has left the {Locker} is
/// force-closed by `closeStaleListing`. The prepaid tax is settled as it is
/// on any other exit: `_feesCaptured` is the elapsed portion booked as fees,
/// `_refunded` the unelapsed remainder credited to `_owner`'s escrow.
event ListingClosedAsStale(address indexed _collection, uint _tokenId, address _owner, uint _feesCaptured, uint _refunded);
/// Emitted when a listing duration is extended
event ListingExtended(address indexed _collection, uint _tokenId, uint32 _oldDuration, uint32 _newDuration);
/// Emitted when a listing floor multiple is updated
event ListingFloorMultipleUpdated(address indexed _collection, uint _tokenId, uint32 _oldFloorMultiple, uint32 _newFloorMultiple);
/// Emitted when listing fees have been captured
event ListingFeeCaptured(address indexed _collection, uint _tokenId, uint _amount);
/// Emitted when the protocol's relative share of a listing fee is routed to the AMM beneficiary
event ListingFeeProtocolCaptured(address indexed _collection, address _beneficiary, uint _amount);
/// Emitted when the default tax calculator is updated
event DefaultTaxCalculatorUpdated(address _taxCalculator);
/// Emitted when a per-collection tax-calculator override is set (non-zero
/// `_taxCalculator`) or cleared (zero `_taxCalculator`)
event CollectionTaxCalculatorUpdated(address indexed _collection, address _taxCalculator);
/// Emitted when the default {ListingConfig} is updated
event DefaultListingConfigUpdated(ListingConfig _config);
/// Emitted when a per-collection {ListingConfig} override is set or
/// cleared (`_config.maxFloorMultiple == 0` indicates a clear)
event CollectionListingConfigUpdated(address indexed _collection, ListingConfig _config);
/**
* The data structure for a listing.
*
* @dev The type of this collection is not defined inside this structure, but can
* be determined by the contents of this structure by using the `getListingType` function.
*
* @custom:member owner Address that can manage and owns the listing
* @custom:member created Timestamp of listing creation
* @custom:member duration Prepaid duration of the listing in seconds
* @custom:member floorMultiple Multiple price of the floor token (2dp accuracy)
*/
struct Listing {
address payable owner;
uint40 created;
uint32 duration;
uint16 floorMultiple;
}
/**
* Data structure provided when creating a listing
*
* @dev Each tokenId specified will follow the same {Listing} structure
*
* @custom:member collection The collection address of the assets being listed
* @custom:member tokenIds An array of the tokenIds being listed
* @custom:member listing A {Listing} data structure defining the listing type
*/
struct CreateListing {
address collection;
uint[] tokenIds;
Listing listing;
}
/**
* Data structure to allow for multiple listings to be updated
*/
struct ModifyListing {
uint tokenId;
uint32 duration;
uint16 floorMultiple;
}
/**
* The tunable parameters that frame how listings behave for a given
* collection. A non-zero `maxFloorMultiple` is the sentinel that
* disambiguates "this collection has a per-collection override" from
* "this collection inherits the default config" — that field is
* structurally `> MIN_FLOOR_MULTIPLE (= 100)` in any valid config, so a
* stored zero cannot collide with a legitimate value.
*
* Fields are packed deliberately: `uint16 + 5 * uint32 = 176` bits fits
* in one storage slot.
*
* @custom:member maxFloorMultiple Upper bound (inclusive) on `floorMultiple` for any
* listing on this collection. Two-decimal precision (`100` = 1.00x = floor).
* @custom:member minLiquidDuration Inclusive lower bound on liquid-listing duration
* @custom:member maxLiquidDuration Inclusive upper bound on liquid-listing duration
* @custom:member minDutchDuration Inclusive lower bound on dutch-listing duration
* @custom:member maxDutchDuration Inclusive upper bound on dutch-listing duration; must be
* strictly less than `minLiquidDuration` so `getListingType` can discriminate
* between dutch and liquid windows
* @custom:member liquidDutchDuration Length of the trailing dutch decay applied to an
* expired liquid listing
*/
struct ListingConfig {
uint16 maxFloorMultiple;
uint32 minLiquidDuration;
uint32 maxLiquidDuration;
uint32 minDutchDuration;
uint32 maxDutchDuration;
uint32 liquidDutchDuration;
}
/**
* The tokenIds that are being filled against, grouped by the owner of each
* listing. This grouping is used to optimise gas.
*
* @custom:member collection The collection address of the tokens being filled
* @custom:member tokenIdsOut The tokenIds being filled, grouped by owner
* @custom:member recipient The address to receive the NFTs
* @custom:member maxSpend Hard cap (in CollectionToken units) on the total
* amount the buyer is willing to spend across all listings in this
* call. Counts ONLY buyer-debited amounts: the premium routed to
* listing owners (`totalPrice`) plus the floor-equivalent burned
* from the buyer's wallet (`floorBurn`). The protocol fill fee is
* funded from sellers' prepaid taxes and is intentionally excluded.
* A non-zero value enables sandwich/front-run protection: if
* owners `modifyListings` upward between simulation and execution,
* the fill reverts with `FillCostExceedsMaxSpend`. Pass `0` to
* opt out (back-compat for callers that don't care).
*/
struct FillListingsParams {
address collection;
uint[][] tokenIdsOut;
address recipient;
uint maxSpend;
}
/**
* Parameters for {IListings.relist}.
*
* @dev Grouped into a struct rather than added as a positional argument so
* that the next parameter this call needs is an additive change instead of
* another breaking one — the same shape (and the same `0 == opt out`
* convention) as {FillListingsParams}.
*
* @custom:member listing The replacement listing. `tokenIds` must contain
* exactly one entry; a longer array reverts rather than silently
* dropping the tail.
* @custom:member payTaxWithEscrow Whether the caller's escrow balance should
* fund the new listing's tax before pulling tokens from their wallet.
* @custom:member maxPrice Ceiling (in CollectionToken units) on the price of
* the *incumbent* listing being taken over, as reported by
* {getListingPrice}. The relister pays `price - 1 CT` to the incumbent
* owner at the price prevailing in the execution block, so without a
* ceiling the incumbent can front-run with `modifyListings` and raise
* `floorMultiple` to the collection maximum. Excludes the tax on the
* caller's own new listing, which the caller's own parameters
* determine, and is not applied at all where the incumbent is paid
* nothing (a floor item, or a dutch listing already decayed to the
* floor). Pass `0` to opt out. Ordered last to match
* {FillListingsParams.maxSpend}, the precedent this follows.
*/
struct RelistParams {
CreateListing listing;
bool payTaxWithEscrow;
uint maxPrice;
}
function locker() external view returns (ILocker);
function listings(address _collection, uint _tokenId) external view returns (Listing memory);
function listingCount(address _collection) external view returns (uint listings_);
/// Default tax calculator used when a collection has no override registered.
function defaultTaxCalculator() external view returns (ITaxCalculator);
/// Raw per-collection tax-calculator override (zero address means "use default").
function collectionTaxCalculator(address _collection) external view returns (ITaxCalculator);
/// Effective tax calculator for `_collection` after applying the override-or-default fallback.
function taxCalculator(address _collection) external view returns (ITaxCalculator);
/// Default {ListingConfig} used when a collection has no override registered.
function defaultListingConfig()
external
view
returns (
uint16 maxFloorMultiple,
uint32 minLiquidDuration,
uint32 maxLiquidDuration,
uint32 minDutchDuration,
uint32 maxDutchDuration,
uint32 liquidDutchDuration
);
/// Raw per-collection {ListingConfig} override; all-zero means "use default".
function collectionListingConfig(address _collection)
external
view
returns (
uint16 maxFloorMultiple,
uint32 minLiquidDuration,
uint32 maxLiquidDuration,
uint32 minDutchDuration,
uint32 maxDutchDuration,
uint32 liquidDutchDuration
);
/// Effective {ListingConfig} for `_collection` after applying the override-or-default fallback.
function listingConfig(address _collection) external view returns (ListingConfig memory);
function setDefaultTaxCalculator(address _taxCalculator) external;
function setCollectionTaxCalculator(address _collection, address _taxCalculator) external;
function setDefaultListingConfig(ListingConfig calldata _config) external;
function setCollectionListingConfig(address _collection, ListingConfig calldata _config) external;
function createListings(CreateListing[] calldata _createListings) external;
function modifyListings(address _collection, ModifyListing[] calldata _modifyListings, bool _payTaxWithEscrow)
external
returns (uint taxRequired_, uint refund_);
function cancelListings(address _collection, uint[] calldata _tokenIds, bool _payTaxWithEscrow) external;
/// Permissionlessly closes a listing whose backing NFT is no longer held by
/// the {Locker}. Reverts unless the collection reports the token as no longer
/// held — which is only as reliable as the collection; see the trust
/// assumption documented on the implementation.
function closeStaleListing(address _collection, uint _tokenId) external;
/// External shim over the library `ownerOf` dispatch, so that ownership reads
/// can be wrapped in `try`/`catch`. Declared here rather than left off the
/// interface because `closeStaleListing`'s precondition is defined in terms
/// of it, and an integrator reproducing that precondition off-chain needs the
/// same read (including the pre-standard CryptoPunks dispatch) rather than a
/// bare `IERC721.ownerOf`.
function nftOwnerOf(address _collection, uint _tokenId) external view returns (address owner_);
function transferOwnership(address _collection, uint _tokenId, address payable _newOwner) external;
function fillListings(FillListingsParams calldata params) external returns (uint totalBurn_);
function relist(RelistParams calldata params) external;
function getListingTaxRequired(Listing memory _listing, address _collection) external returns (uint taxRequired_);
function getListingPrice(address _collection, uint _tokenId) external view returns (bool isAvailable_, uint price_);
function getListingType(address _collection, Listing memory _listing) external view returns (Enums.ListingType);
}
src/interfaces/ILocker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {ICollectionLaunchGate} from 'nftx-interfaces/ICollectionLaunchGate.sol';
import {ICollectionToken} from 'nftx-interfaces/ICollectionToken.sol';
import {IListings} from 'nftx-interfaces/IListings.sol';
import {ILockerManager} from 'nftx-interfaces/ILockerManager.sol';
import {INFTXV4Hook} from 'nftx-interfaces/INFTXV4Hook.sol';
import {ICollectionShutdown} from 'nftx-interfaces/utils/ICollectionShutdown.sol';
interface ILocker {
error InvalidTokenImplementation();
error CollectionAlreadyInitialized();
/// Reverts when a single-sided (zero-native) launch is attempted but the
/// wired {ICollectionLaunchGate} does not permit single-sided liquidity
error SingleSidedNotAllowed();
error TokenIsListing(uint _tokenId);
error CannotSwapSameToken();
error NoTokenIds();
error TokenIdsLengthMismatch();
error CollectionAlreadyExists();
error InvalidERC721();
error CallerIsNotManager();
error InsufficientTokenIds();
error InvalidCaller();
error ZeroAddress();
error CannotChangeImplementation();
error CollectionDoesNotExist();
error CollectionCreationFeeDoesNotMatch(uint _received, uint _required);
error ETHTransferFailed();
/// Reverts when {addListings} is called with a contract already in the set
error ListingsAlreadyRegistered(address _listings);
/// Reverts when {removeListings} is called with a contract that is not
/// registered
error ListingsNotRegistered(address _listings);
/// Reverts when {addListings} is called with an address that holds no
/// code. Registering an EOA used to succeed and permanently brick
/// {isListing}, and with it every NFT exit from the {Locker}.
error ListingsNotAContract(address _listings);
/// Reverts when {addListings} is called with a contract that does not
/// answer the {IListings} conformance probe. Covers both a target that
/// reverts and one that returns nothing.
error ListingsProbeFailed(address _listings);
/// Reverts when {addListings} would grow the registered set beyond
/// `MAX_REGISTERED_LISTINGS`. That set is iterated by {isListing} on every
/// released tokenId, so its size is capped to keep the fan-out priceable.
error TooManyListingsRegistered(uint _max);
/// Reverts when {createCollection} is called for a `_collection` address
/// that has already been sunset. Prevents split-state risk from
/// re-registering an address whose previous CollectionToken supply,
/// shutdown votes, and sweeper-pool state may still be circulating.
error CollectionPreviouslySunset();
/// Emitted when a collection has been created
event CollectionCreated(address indexed _collection, address _collectionToken, string _name, string _symbol, address _creator);
/// Emitted when a collection has been initialized with tokens and a price
event CollectionInitialized(address indexed _collection, bytes _poolKey, uint[] _tokenIds, uint _sqrtPriceX96, address _sender);
/// Emitted when a collection is shutdown
event CollectionSunset(address indexed _collection, address _collectionToken, address _sender);
/// Emitted when floor tokens have been depositted to mint ERC20s
event TokenDeposit(address indexed _collection, uint[] _tokenIds, address _sender, address _recipient);
/// Emitted when ERC20 tokens are redeemed against floor tokens
event TokenRedeem(address indexed _collection, uint[] _tokenIds, address _sender, address _recipient);
/// Emitted when a token is swapped for another token from the same collection
event TokenSwap(address indexed _collection, uint _tokenIdIn, uint _tokenIdOut, address _sender);
/// Emitted when multiple tokens are swapped for an equal number of other tokens
/// from the same collection.
event TokenSwapBatch(address indexed _collection, uint[] _tokenIdsIn, uint[] _tokenIdsOut, address _sender);
/// Emitted when a {LockerManager} manager releases a token from the {Locker}.
///
/// @dev This is the only path by which an NFT leaves the {Locker} without a
/// `TokenRedeem` or `TokenSwap`, and it previously emitted nothing at all —
/// so a manager withdrawal was invisible to indexers and every vault count
/// derived from events over-counted from that moment on. `_sender` is the
/// manager, which is a protocol contract on the in-band paths
/// ({Listings.cancelListings}, {Listings._fillListing},
/// {CollectionShutdown.execute}) and an operator address otherwise.
event TokenWithdrawal(address indexed _collection, uint _tokenId, address _sender, address _recipient);
/// Emitted when an authorised {Listings} contract is registered against
/// this {Locker}
event ListingsContractAdded(address _listings);
/// Emitted when an authorised {Listings} contract is de-registered
event ListingsContractRemoved(address _listings);
/// Emitted when the {CollectionShutdown} contract is updated
event CollectionShutdownContractUpdated(address _collectionShutdown);
/// Emitted when the external collection launch gate is updated
event LaunchGateUpdated(address _launchGate);
function tokenImplementation() external view returns (address);
function implementation() external view returns (INFTXV4Hook);
function lockerManager() external view returns (ILockerManager);
function listingsAt(uint _index) external view returns (IListings);
function isListings(address _target) external view returns (bool);
function listingsLength() external view returns (uint);
function MAX_REGISTERED_LISTINGS() external view returns (uint);
function collectionShutdown() external view returns (ICollectionShutdown);
function collectionToken(address _collection) external view returns (ICollectionToken);
function collectionInitialized(address _collection) external view returns (bool);
function isCollectionToken(address _token) external view returns (bool);
function collectionSunset(address _collection) external view returns (bool);
function deposit(address _collection, uint[] calldata _tokenIds) external;
function deposit(address _collection, uint[] calldata _tokenIds, address _recipient) external;
function redeem(address _collection, uint[] calldata _tokenIds) external;
function redeem(address _collection, uint[] calldata _tokenIds, address _recipient) external;
function swap(address _collection, uint _tokenIdIn, uint _tokenIdOut) external;
function swapBatch(address _collection, uint[] calldata _tokenIdsIn, uint[] calldata _tokenIdsOut) external;
function createCollection(address _collection, string calldata _name, string calldata _symbol) external payable returns (address);
function initializeCollection(address _collection, uint _eth, uint[] calldata _tokenIds, uint _tokenSlippage, uint160 _sqrtPriceX96)
external;
function sunsetCollection(address _collection) external;
function withdrawToken(address _collection, uint _tokenId, address _recipient) external;
function isListing(address _collection, uint _tokenId) external view returns (bool);
function addListings(address _listings) external;
/// Destructive, **not** a routine migration step. See the implementation's
/// NatSpec: de-registering a {Listings} contract unprotects every listing
/// it still holds open.
function removeListings(address _listings) external;
function setCollectionShutdownContract(address payable _collectionShutdown) external;
/// The fee {createCollection} currently charges: the wired {launchGate}'s fee,
/// or zero when no gate is set
function getCollectionCreationFee() external view returns (uint);
function launchGate() external view returns (ICollectionLaunchGate);
function setLaunchGate(address _launchGate) external;
function pause(bool _paused) external;
function paused() external view returns (bool);
}
src/interfaces/ILockerManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
interface ILockerManager {
error ManagerIsZeroAddress();
error StateAlreadySet();
function setManager(address _manager, bool _approved) external;
function isManager(address _manager) external view returns (bool);
}
src/interfaces/INFTXV4Hook.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {PoolId} from '@uniswap/v4-core/src/types/PoolId.sol';
import {ICollectionToken} from 'nftx-interfaces/ICollectionToken.sol';
import {INotifier} from 'nftx-interfaces/INotifier.sol';
/**
* Single source of truth for the public surface of the {NFTXV4Hook} — the
* sole Uniswap V4 backed implementation registered on the {Locker}. Errors,
* events, structs, and external function signatures all live here so the
* frontend / subgraph / integrators only need a single import.
*/
interface INFTXV4Hook {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
error NotImplemented();
error ZeroAddress();
/// Reverts when {initializeCollection} is called with a zero recipient
/// for the LP NFT minted by the canonical V4 PositionManager
error LPRecipientIsZeroAddress();
/// Reverts when a collection has not been registered via
/// {registerCollection} prior to a hook lookup
error UnknownCollection();
/// Reverts when the V4 pool initialize entry-point is invoked outside
/// the canonical {initializeCollection} flow
error CannotBeInitializedDirectly();
/// Reverts when a hook callback fires before {initializeCollection}
/// has flipped the pool to initialized
error PoolNotInitialized();
/// Reverts when a swap or an add-liquidity targets a pool whose collection
/// the {Locker} has sunset. Removing liquidity stays open so LPs can exit
error PoolDeregistered();
/// Reverts when a privileged hook entry-point is invoked by anyone
/// other than the registered {Locker}
error CallerIsNotLocker();
/// Reverts when {depositFees} is called by anything other than a {Listings}
/// contract registered against the {Locker}
error CallerIsNotListings();
/// Reverts when {setFeeExemption} is called with a fee value above the
/// V4 max LP fee
error FeeExemptionInvalid(uint24 _invalidFee, uint24 _maxFee);
/// Reverts when {removeFeeExemption} is called for a beneficiary that
/// has no active exemption
error NoBeneficiaryExemption(address _beneficiary);
/// Reverts when the liquidity computed for a launch is zero — e.g. a zero
/// collection-token amount, or amounts that round down to no liquidity
error ZeroLiquidity();
/// Reverts when the derived tick range is degenerate (`tickLower >= tickUpper`).
/// Only reachable for a single-sided launch whose price sits at the extreme
/// usable tick, collapsing the one-sided range.
error InvalidLiquidityRange();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// Emitted when the {Locker} sunsets a collection and its pool is retired
event CollectionDeregistered(address indexed _collection, PoolId _poolId);
/// Emitted when fees are queued for a collection pool
event PoolFeesQueued(address indexed _collection, uint _amount0, uint _amount1);
/// Emitted when a pool has been allocated fees on either side of the position
event PoolFeesDonated(address indexed _collection, uint _amount0, uint _amount1);
/// Emitted after any transaction to share pool state
event PoolStateUpdated(
address indexed _collection, uint160 _sqrtPriceX96, int24 _tick, uint24 _protocolFee, uint24 _swapFee, uint128 _liquidity
);
/// Emitted when a new default fee is set
event DefaultFeeSet(uint24 _fee);
/// Emitted when a Pool fee is set
event PoolFeeSet(address indexed _collection, uint24 _fee);
/// Emitted when the AMM Fee is updated
event AMMFeeSet(uint24 _ammFee);
/// Emitted when the AMM beneficiary address is updated
event AMMBeneficiarySet(address _ammBeneficiary);
/// Emitted when AMM fees are captured
event AMMFeesTaken(address _recipient, address _token, uint _amount);
/// Emitted when a beneficiary fee override is set or updated
event FeeOverrideSet(address _beneficiary, uint24 _flatFee);
/// Emitted when a beneficiary fee override is removed
event FeeOverrideRemoved(address _beneficiary);
/// Emitted when the {INotifier} consulted at each hook point is set or detached
event NotifierSet(address _notifier);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/**
* Per-pool parameters tracked by the hook.
*
* @custom:member collection The ERC721 collection address backing the pool
* @custom:member poolFee Per-pool LP fee override (0 falls back to {defaultFee})
* @custom:member initialized True once {initializeCollection} has succeeded
* @custom:member currencyFlipped True when `nativeToken > collectionToken`,
* i.e. the collection sits on `currency0` and native on `currency1`
* @custom:member deregistered True once {deregisterCollection} has run, i.e. the
* {Locker} has sunset the collection. Terminal — see audit R-08
*/
struct PoolParams {
address collection;
uint24 poolFee;
bool initialized;
bool currencyFlipped;
bool deregistered;
}
/**
* Fees queued via {depositFees} but not yet routed into the pool. They
* are donated to LPs in the next hook callback that unlocks the
* {PoolManager}.
*
* @custom:member amount0 Amount queued in the pool's `currency0`
* @custom:member amount1 Amount queued in the pool's `currency1`
*/
struct PendingDonation {
uint128 amount0;
uint128 amount1;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REGISTRATION */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:°•.°+.*•´.*:*/
/**
* @param _collection The address of the collection being registered
* @param _collectionToken The underlying ERC20 token for the collection
*/
function registerCollection(address _collection, ICollectionToken _collectionToken) external;
/**
* Retires a collection's pool once the {Locker} has sunset it. Callable only by
* the {Locker}. Terminal: swaps and new liquidity are refused from this point on,
* while removing liquidity stays open so LPs can exit. See audit R-08.
*
* @param _collection The address of the collection being retired
*/
function deregisterCollection(address _collection) external;
/**
* @param _collection The address of the collection being initialized
* @param _eth The amount of ETH equivalent tokens being passed in
* @param _tokens The number of underlying tokens being supplied
* @param _amount1Slippage The amount of slippage allowed in underlying token
* @param _sqrtPriceX96 The intiail pool price
* @param _recipient The recipient of the LP NFT minted by the V4 PositionManager
*/
function initializeCollection(
address _collection,
uint _eth,
uint _tokens,
uint _amount1Slippage,
uint160 _sqrtPriceX96,
address _recipient
) external;
/**
* @dev Amounts are denominated in the pool's V4-sorted currency order
* (currency0 < currency1 by address), NOT in "native vs collection"
* semantics. Callers must resolve the active orientation themselves —
* typically by comparing `nativeToken()` against the collection token
* address — and pass the fee in the slot that corresponds to the side
* they are funding. Passing the collection-token fee in the wrong slot
* will revert because the matching ERC20 will not be approved against
* the implementation.
*
* @param _collection The address of the collection
* @param _amount0 Fees denominated in `currency0` (post-V4 sort)
* @param _amount1 Fees denominated in `currency1` (post-V4 sort)
*/
function depositFees(address _collection, uint _amount0, uint _amount1) external;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* VIEWS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:°•.°+.*•´.*:*/
/// The ETH-equivalent ERC20 paired against each `CollectionToken`
function nativeToken() external view returns (address _token);
/**
* @param _collection The address of the collection
* @return The encoded `PoolKey` for the collection
*/
function getCollectionPoolKey(address _collection) external view returns (bytes memory);
/**
* @param _poolId The id of the pool to look up
* @return PoolParams The on-chain pool parameters
*/
function poolParams(PoolId _poolId) external view returns (PoolParams memory);
/**
* Fees queued via {depositFees} that have not yet reached the pool's LPs. Non-zero
* means the pool had no active in-range liquidity on the last hook call and the
* donation was deferred. See audit A-12.
*
* @param _poolId The id of the pool to look up
* @return PendingDonation The outstanding amounts, in V4 currency order
*/
function pendingDonations(PoolId _poolId) external view returns (PendingDonation memory);
/**
* Resolve the dynamic fee for `_poolId` for a swap initiated by `_origin`.
*
* @param _poolId The id of the pool
* @param _origin The origin of the swap (e.g. `tx.origin`)
* @return fee_ The dynamic fee in V4 pip units (`1_000_000` == 100%)
*/
function getFee(PoolId _poolId, address _origin) external view returns (uint24 fee_);
/// Effective base LP fee for a collection's pool (ignores per-origin swap exemptions)
function getCollectionFee(address _collection) external view returns (uint24 fee_);
/// Per-beneficiary swap-fee override, encoded as `(flatFee << 24) | 0xFFFFFF`
/// when active. Zero when the beneficiary has no override.
function feeOverrides(address _beneficiary) external view returns (uint48);
/// Default LP fee applied when a pool does not override it
function defaultFee() external view returns (uint24);
/// Additional fee taken from the unspecified leg of every swap and
/// credited to {ammBeneficiary} via the inherited {TokenEscrow}
function ammFee() external view returns (uint24);
/// Beneficiary of the AMM fee
function ammBeneficiary() external view returns (address);
/// The external {INotifier} fanned out to at each hook point. Zero when unset, in which
/// case every hook point is skipped and the hook behaves exactly as if it had none.
function notifier() external view returns (INotifier);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ADMIN */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:°•.°+.*•´.*:*/
/// Set the protocol-wide default LP fee
function setDefaultFee(uint24 _defaultFee) external;
/// Set a per-pool LP fee override
function setFee(PoolId _poolId, uint24 _fee) external;
/// Set the AMM fee taken from the unspecified leg of every swap
function setAmmFee(uint24 _ammFee) external;
/// Set the AMM beneficiary that receives AMM fees
function setAmmBeneficiary(address _ammBeneficiary) external;
/// Configure a flat-fee override for a beneficiary
function setFeeExemption(address _beneficiary, uint24 _flatFee) external;
/// Remove the flat-fee override for a beneficiary
function removeFeeExemption(address _beneficiary) external;
/**
* Attach an {INotifier} to fan hook points out to its registered subscribers, or pass
* `address(0)` to detach and return the hook to its stand-alone behaviour.
*
* @dev Subscribers are trusted: their reverts are not isolated and will fail the
* originating swap or collection registration. See {ISubscriber}.
*
* @param _notifier The new notifier address (or `address(0)` to detach)
*/
function setNotifier(address _notifier) external;
}
src/interfaces/INotifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {BalanceDelta} from '@uniswap/v4-core/src/types/BalanceDelta.sol';
import {PoolId} from '@uniswap/v4-core/src/types/PoolId.sol';
import {PoolKey} from '@uniswap/v4-core/src/types/PoolKey.sol';
import {SwapParams} from '@uniswap/v4-core/src/types/PoolOperation.sol';
import {HookPoint} from 'nftx-interfaces/ISubscriber.sol';
/**
* Single source of truth for the public surface of the {Notifier} — the fan-out point that
* sits between the {NFTXV4Hook} and any registered {ISubscriber}.
*
* The hook makes exactly one call per hook point; the {Notifier} then dispatches it to only
* those subscribers registered against that point, identified by the {HookPoint} enum
* declared in `ISubscriber.sol`. A subscriber is registered against one point per call, so
* covering several points means several {subscribe} calls.
*/
interface INotifier {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// Reverts when a fan-out entry-point is invoked by anyone other than the registered hook
error CallerIsNotHook();
/// Reverts when the hook or a subscriber is supplied as a zero address
error ZeroAddress();
/// Reverts when {subscribe} is called for an address already registered against the point
error AlreadySubscribed(address _subscriber);
/// Reverts when {unsubscribe} is called for an address not registered against the point
error SubscriberNotFound(address _subscriber);
/// Reverts when the folded {ISubscriber.updateFee} result exceeds the V4 max LP fee
error SubscriberFeeInvalid(uint24 _invalidFee, uint24 _maxFee);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// Emitted when a subscriber is registered against a hook point
event SubscriberAdded(address indexed _subscriber, HookPoint _point);
/// Emitted when a subscriber is removed from a hook point
event SubscriberRemoved(address indexed _subscriber, HookPoint _point);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* FAN-OUT */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// Fans {ISubscriber.validateCollection} out to the subscribers of that hook point
function validateCollection(address _collection, address _collectionToken) external;
/// Fans {ISubscriber.validateSwap} out to the subscribers of that hook point
function validateSwap(address _sender, PoolKey calldata _poolKey, SwapParams calldata _params, bytes calldata _hookData) external;
/// Fans {ISubscriber.notifySwap} out to the subscribers of that hook point
function notifySwap(
address _sender,
PoolKey calldata _poolKey,
SwapParams calldata _params,
BalanceDelta _delta,
bytes calldata _hookData
) external;
/**
* Folds the fee through every {ISubscriber} registered against the fee hook point, each
* receiving the running value produced by the last.
*
* @param _poolId The ID of the pool being swapped against
* @param _origin The origin of the swap
* @param _fee The fee resolved by the hook, in V4 pip units
*
* @return fee_ The folded fee, validated against `LPFeeLibrary.MAX_LP_FEE`
*/
function updateFee(PoolId _poolId, address _origin, uint24 _fee) external view returns (uint24 fee_);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ADMIN */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/**
* Registers `_subscriber` against a single hook point.
*
* @dev Subscribers are trusted. Their reverts are not isolated and will fail the
* originating swap or collection registration — see {ISubscriber}.
*
* @param _subscriber The {ISubscriber} contract to register
* @param _point The hook point to register it against
*/
function subscribe(address _subscriber, HookPoint _point) external;
/**
* Removes `_subscriber` from a single hook point.
*
* @param _subscriber The {ISubscriber} contract to remove
* @param _point The hook point to remove it from
*/
function unsubscribe(address _subscriber, HookPoint _point) external;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* VIEWS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// The {NFTXV4Hook} permitted to drive this notifier
function hook() external view returns (address);
/**
* Lists the subscribers registered against a single hook point.
*
* @param _point The hook point to list
* @return subscribers_ The registered subscriber addresses, in unspecified order
*/
function subscribers(HookPoint _point) external view returns (address[] memory subscribers_);
}
src/interfaces/ISubscriber.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {BalanceDelta} from '@uniswap/v4-core/src/types/BalanceDelta.sol';
import {PoolId} from '@uniswap/v4-core/src/types/PoolId.sol';
import {PoolKey} from '@uniswap/v4-core/src/types/PoolKey.sol';
import {SwapParams} from '@uniswap/v4-core/src/types/PoolOperation.sol';
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOK POINTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
enum HookPoint {
VALIDATE_COLLECTION,
VALIDATE_SWAP,
NOTIFY_SWAP,
UPDATE_FEE
}
/**
* External, owner-curated policy contract that the {Notifier} fans hook calls out to on
* behalf of the {NFTXV4Hook}. A subscriber only receives the hook points it was registered
* against, so an `updateFee`-only subscriber is never touched on the swap path.
*
* @dev Subscribers are a trusted, owner-gated role. Reverts are **not** isolated — a revert
* in any of these methods propagates all the way out and will fail the originating swap or
* collection registration. `updateFee` additionally feeds {Listings}, so a subscriber that
* reverts there breaks listing tax splitting as well as swaps. Recovery is
* {INotifier.unsubscribe}.
*
* Implementations must not re-enter the {PoolManager}. `validateSwap` and `notifySwap` are
* both invoked while the manager is unlocked and mid-swap, and `notifySwap` in particular
* runs after the hook has already taken its AMM fee but before it returns its delta.
*/
interface ISubscriber {
/**
* Called as a collection is registered against the hook, before any pool state is written.
* Revert to reject the collection.
*
* @param _collection The address of the collection being registered
* @param _collectionToken The underlying ERC20 token for the collection
*/
function validateCollection(address _collection, address _collectionToken) external;
/**
* Called at the top of the hook's `beforeSwap` callback, before the dynamic fee is
* resolved and before any queued fees are donated. Revert to reject the swap.
*
* @param _sender The address that initiated the swap against the {PoolManager}
* @param _poolKey The Uniswap V4 pool key
* @param _params The swap parameters
* @param _hookData Arbitrary data forwarded by the swap router
*/
function validateSwap(address _sender, PoolKey calldata _poolKey, SwapParams calldata _params, bytes calldata _hookData) external;
/**
* Called at the end of the hook's `afterSwap` callback, once the AMM fee has been taken
* and the pool state update emitted.
*
* @param _sender The address that initiated the swap against the {PoolManager}
* @param _poolKey The Uniswap V4 pool key
* @param _params The swap parameters
* @param _delta The resulting swap delta
* @param _hookData Arbitrary data forwarded by the swap router
*/
function notifySwap(
address _sender,
PoolKey calldata _poolKey,
SwapParams calldata _params,
BalanceDelta _delta,
bytes calldata _hookData
) external;
/**
* Called as the final step of {NFTXV4Hook.getFee} to adjust the resolved dynamic fee.
*
* @dev This must be `view` because it is reached through the `view` {NFTXV4Hook.getFee},
* i.e. it is always a staticcall.
*
* Fee subscribers are folded: each receives the running fee produced by the preceding
* subscriber and returns a replacement. Iteration order is **not** stable across
* unsubscribes, so implementations should be order-independent (a `min` clamp or a
* multiplicative discount) rather than depending on their position in the chain.
*
* The value the fold settles on is validated against `LPFeeLibrary.MAX_LP_FEE` by the
* {Notifier}, so returning an out-of-range fee reverts the swap.
*
* @param _poolId The ID of the pool being swapped against
* @param _origin The origin of the swap, as passed to {NFTXV4Hook.getFee}
* @param _fee The running fee in V4 pip units (`1_000_000` == 100%)
*
* @return fee_ The replacement fee in V4 pip units
*/
function updateFee(PoolId _poolId, address _origin, uint24 _fee) external view returns (uint24 fee_);
}
src/interfaces/ITaxCalculator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
interface ITaxCalculator {
function calculateTax(address _collection, uint _floorMultiple, uint _duration) external view returns (uint);
}
src/interfaces/ITokenEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
interface ITokenEscrow {
error CannotWithdrawZeroAmount();
error InsufficientBalanceAvailable();
error RecipientIsZeroAddress();
/// Emitted when a deposit has been made
event Deposit(address indexed _payee, address _token, uint _amount, address _sender);
/// Emitted when a withdrawal has been made
event Withdrawal(address indexed _payee, address indexed _recipient, address _token, uint _amount);
/// Sentinel `_token` value routing a transfer to the chain's native token instead of an ERC20
function NATIVE_TOKEN() external view returns (address);
/// Gets the balance of a recipient for a token
function balances(address _recipient, address _token) external view returns (uint amount_);
/// Allows a user to withdraw from their escrow position
function withdraw(address _recipient, address _token, uint _amount) external;
}
src/interfaces/lssvm2/CurveErrorCodes.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.26;
contract CurveErrorCodes {
enum Error {
OK, // No error
INVALID_NUMITEMS, // The numItem value is 0
SPOT_PRICE_OVERFLOW, // The updated spot price doesn't fit into 128 bits
DELTA_OVERFLOW, // The updated delta doesn't fit into 128 bits
SPOT_PRICE_UNDERFLOW, // The updated spot price goes too low
AUCTION_ENDED // The auction has ended
}
}
src/interfaces/lssvm2/ICurve.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.26;
import {CurveErrorCodes} from 'nftx-interfaces/lssvm2/CurveErrorCodes.sol';
interface ICurve {
/**
* @notice Validates if a delta value is valid for the curve. The criteria for
* validity can be different for each type of curve, for instance ExponentialCurve
* requires delta to be greater than 1.
* @param delta The delta value to be validated
* @return valid True if delta is valid, false otherwise
*/
function validateDelta(uint128 delta) external pure returns (bool valid);
/**
* @notice Validates if a new spot price is valid for the curve. Spot price is generally assumed to be the immediate sell price of 1 NFT to the pool, in units of the pool's paired token.
* @param newSpotPrice The new spot price to be set
* @return valid True if the new spot price is valid, false otherwise
*/
function validateSpotPrice(uint128 newSpotPrice) external view returns (bool valid);
/**
* @notice Given the current state of the pair and the trade, computes how much the user
* should pay to purchase an NFT from the pair, the new spot price, and other values.
* @param spotPrice The current selling spot price of the pair, in tokens
* @param delta The delta parameter of the pair, what it means depends on the curve
* @param numItems The number of NFTs the user is buying from the pair
* @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
* @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
* @return error Any math calculation errors, only Error.OK means the returned values are valid
* @return newSpotPrice The updated selling spot price, in tokens
* @return newDelta The updated delta, used to parameterize the bonding curve
* @return inputValue The amount that the user should pay, in tokens
* @return tradeFee The amount that is sent to the trade fee recipient
* @return protocolFee The amount of fee to send to the protocol, in tokens
*/
function getBuyInfo(uint128 spotPrice, uint128 delta, uint numItems, uint feeMultiplier, uint protocolFeeMultiplier)
external
view
returns (CurveErrorCodes.Error error, uint128 newSpotPrice, uint128 newDelta, uint inputValue, uint tradeFee, uint protocolFee);
/**
* @notice Given the current state of the pair and the trade, computes how much the user
* should receive when selling NFTs to the pair, the new spot price, and other values.
* @param spotPrice The current selling spot price of the pair, in tokens
* @param delta The delta parameter of the pair, what it means depends on the curve
* @param numItems The number of NFTs the user is selling to the pair
* @param feeMultiplier Determines how much fee the LP takes from this trade, 18 decimals
* @param protocolFeeMultiplier Determines how much fee the protocol takes from this trade, 18 decimals
* @return error Any math calculation errors, only Error.OK means the returned values are valid
* @return newSpotPrice The updated selling spot price, in tokens
* @return newDelta The updated delta, used to parameterize the bonding curve
* @return outputValue The amount that the user should receive, in tokens
* @return tradeFee The amount that is sent to the trade fee recipient
* @return protocolFee The amount of fee to send to the protocol, in tokens
*/
function getSellInfo(uint128 spotPrice, uint128 delta, uint numItems, uint feeMultiplier, uint protocolFeeMultiplier)
external
view
returns (CurveErrorCodes.Error error, uint128 newSpotPrice, uint128 newDelta, uint outputValue, uint tradeFee, uint protocolFee);
}
src/interfaces/lssvm2/ILSSVMPair.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.26;
import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {CurveErrorCodes} from 'nftx-interfaces/lssvm2/CurveErrorCodes.sol';
import {ICurve} from 'nftx-interfaces/lssvm2/ICurve.sol';
/**
* Stripped down `ILSSVMPair` interface with `LSSVMPairETH` function references:
* https://github.com/sudoswap/lssvm2/blob/main/src/ILSSVMPair.sol
*/
interface ILSSVMPair {
enum PoolType {
TOKEN,
NFT,
TRADE
}
function getBuyNFTQuote(uint assetId, uint numItems)
external
view
returns (CurveErrorCodes.Error error, uint newSpotPrice, uint newDelta, uint inputAmount, uint protocolFee, uint royaltyAmount);
function getSellNFTQuote(uint assetId, uint numNFTs)
external
view
returns (CurveErrorCodes.Error error, uint newSpotPrice, uint newDelta, uint outputAmount, uint protocolFee, uint royaltyAmount);
function bondingCurve() external view returns (ICurve);
}
src/interfaces/lssvm2/ILSSVMPairFactoryLike.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.26;
import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {ICurve} from 'nftx-interfaces/lssvm2/ICurve.sol';
import {ILSSVMPair} from 'nftx-interfaces/lssvm2/ILSSVMPair.sol';
/**
* Stripped down `ILSSVMPairFactoryLike` interface:
* https://github.com/sudoswap/lssvm2/blob/main/src/ILSSVMPairFactoryLike.sol
*/
interface ILSSVMPairFactoryLike {
function createPairERC721ETH(
IERC721 _nft,
ICurve _bondingCurve,
address payable _assetRecipient,
ILSSVMPair.PoolType _poolType,
uint128 _delta,
uint96 _fee,
uint128 _spotPrice,
address _propertyChecker,
uint[] calldata _initialNFTIDs
) external payable returns (address);
function setBondingCurveAllowed(ICurve, bool) external;
}
src/interfaces/utils/ICollectionShutdown.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {ICollectionToken} from 'nftx-interfaces/ICollectionToken.sol';
import {ILocker} from 'nftx-interfaces/ILocker.sol';
import {ICurve} from 'nftx-interfaces/lssvm2/ICurve.sol';
import {ILSSVMPairFactoryLike} from 'nftx-interfaces/lssvm2/ILSSVMPairFactoryLike.sol';
interface ICollectionShutdown {
/// Error when zero address is provided for the locker
error LockerIsZeroAddress();
error ShutdownPrevented();
error ShutdownProcessAlreadyStarted();
error ShutdownProccessNotStarted();
error ShutdownNotReachedQuorum();
error ShutdownNotExecuted();
/// @dev No longer thrown. `reclaimVote` used to refuse outright once quorum was
/// reached; it now recomputes the flag instead, because nothing guaranteed the
/// pending execution would ever land and voters were held hostage in the
/// meantime (audit R-03). Retained so integrators decoding historical reverts
/// and existing ABIs do not break.
error ShutdownQuorumHasPassed();
/// Reverts when `vote`, `reclaimVote` or `cancel` is called on a collection
/// whose shutdown has already been executed. Execution is terminal: the
/// NFTs are irreversibly with the sweeper pool by that point.
error ShutdownAlreadyExecuted();
error TooManyItems();
error UserHoldsNoTokens();
error NoNFTsSupplied();
error ListingsExist();
error NoTokensAvailableToClaim();
error NotAllTokensSold();
error FailedToClaim();
error NoVotesPlacedYet();
error InsufficientTotalSupplyToCancel();
error CollectionNotShutdownCompatible(address _collection);
/// Emitted when a collection shutdown process has been started
event CollectionShutdownStarted(address _collection);
/// Emitted when a collection shutdown process has been cancelled
event CollectionShutdownCancelled(address _collection);
/// Emitted when the contract owner stands a shutdown round down via
/// `abortShutdown`. Distinct from {CollectionShutdownCancelled} so the
/// permissionless and owner-driven paths are separable off-chain.
event CollectionShutdownAborted(address _collection);
/// Emitted when the contract owner overrides the liquidation-completion probe
event CollectionLiquidationCompleteOverride(address _collection, bool _complete);
/// Emitted when a shutdown has been executed
event CollectionShutdownExecuted(address _collection, address _pool, uint[] _tokenIds);
/// Emitted when a collection shutdown vote has been cast
event CollectionShutdownVote(address _collection, address _voter, uint _vote);
/// Emitted when a collection shutdown vote has been reclaimed
event CollectionShutdownVoteReclaim(address _collection, address _voter, uint _vote);
/// Emitted when a collection shutdown is completed
event CollectionShutdownQuorumReached(address _collection);
/// Emitted when a collection shutdown claim has been made
event CollectionShutdownClaim(address _collection, address _claimant, uint _tokenAmount, uint _ethAmount);
/// Emitted when a SudoSwap tokenId is liquidated and ETH is received
event CollectionShutdownTokenLiquidated(address _collection, uint _ethAmount);
/// Emitted when a collection is prevented from shutdown
event CollectionShutdownPrevention(address _collection, bool _prevented);
/**
* A structure that defines our collection shutdown attributes.
*
* @dev Aside from the uint[] tokenId array, this data struct is packed into 3 blocks.
*
* @custom:member shutdownVotes The number of votes cast to shutdown the collection
* @custom:member sweeperPool The sweeper pool created by the shutdown
* @custom:member quorumVotes The number of votes required to reach a quorum
* @custom:member canExecute If the shutdown can be executed
* @custom:member collectionToken The collection token for the shutdown
* @custom:member availableClaim The amount of ETH available to be claimed
* @custom:member sweeperPoolTokenIds The tokenIds sent into the sweeper pool
*/
struct CollectionShutdownParams {
uint96 shutdownVotes;
address sweeperPool;
uint88 quorumVotes;
bool canExecute;
ICollectionToken collectionToken;
uint availableClaim;
uint[] sweeperPoolTokenIds;
}
function collectionParams(address _collection) external view returns (CollectionShutdownParams memory);
function shutdownVoters(address _collection, address _user) external view returns (uint votes_);
/// The exact {CollectionToken} total supply snapshotted at execution, and the
/// denominator every claim against the collection is divided by.
function claimDenominator(address _collection) external view returns (uint totalSupply_);
function liquidationCompleteOverride(address _collection) external view returns (bool complete_);
function sweeperPoolCollection(address _sudoswapPool) external view returns (address collection_);
function pairFactory() external returns (ILSSVMPairFactoryLike);
function curve() external returns (ICurve);
function locker() external returns (ILocker);
function MAX_SHUTDOWN_TOKENS() external returns (uint);
function SHUTDOWN_QUORUM_PERCENT() external returns (uint);
function start(address _collection) external;
function vote(address _collection) external;
function execute(address _collection, uint[] calldata _tokenIds) external;
function claim(address _collection, address payable _claimant) external;
function voteAndClaim(address _collection) external;
function reclaimVote(address _collection) external;
function cancel(address _collection) external;
function abortShutdown(address _collection) external;
function setLiquidationCompleteOverride(address _collection, bool _complete) external;
function preventShutdown(address _collection, bool _prevent) external;
function pause(bool _paused) external;
function collectionLiquidationComplete(address _collection) external view returns (bool);
function tokenOwner(address _collection, uint _tokenId) external view returns (address);
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 123,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@ensdomains/=lib/v4-hooks-public/lib/v4-core/node_modules/@ensdomains/",
"@eth-optimism-bedrock/=lib/v4-hooks-public/lib/protocol-fees/lib/optimism/packages/contracts-bedrock/",
"@nomad-xyz/=lib/v4-hooks-public/lib/slipstream/lib/ExcessivelySafeCall/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/v4-hooks-public/lib/openzeppelin-contracts/contracts/",
"@pancakeswap/v3-core/=lib/v4-hooks-public/lib/pancake-v3-contracts/projects/v3-core/contracts/",
"@protocol-fees/=lib/v4-hooks-public/lib/protocol-fees/src/",
"@solidity-parser/=lib/v4-hooks-public/lib/slipstream/node_modules/solhint/node_modules/@solidity-parser/",
"@uniswap/blocknumberish/=lib/v4-hooks-public/lib/blocknumberish/",
"@uniswap/v2-core/contracts/=lib/v4-hooks-public/lib/v2-core/contracts/",
"@uniswap/v3-core/=lib/v4-hooks-public/lib/v3-core/",
"@uniswap/v3-periphery/=lib/v4-hooks-public/lib/v3-periphery/",
"@uniswap/v4-core/=lib/v4-hooks-public/lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-hooks-public/lib/v4-periphery/",
"@uniswap-hooks/=lib/v4-hooks-public/src/",
"@uniswap-periphery/=lib/v4-hooks-public/lib/v4-periphery/src/",
"interfaces/=src/interfaces/",
"gates/=src/contracts/gates/",
"libraries/=src/contracts/libraries/",
"oracles/=src/contracts/oracles/",
"utils/=src/contracts/utils/",
"zaps/=src/contracts/zaps/",
"test/=src/contracts/test/",
"CollectionToken.sol=src/contracts/CollectionToken.sol",
"Listings.sol=src/contracts/Listings.sol",
"Locker.sol=src/contracts/Locker.sol",
"LockerManager.sol=src/contracts/LockerManager.sol",
"NFTXV4Hook.sol=src/contracts/NFTXV4Hook.sol",
"TaxCalculator.sol=src/contracts/TaxCalculator.sol",
"TokenEscrow.sol=src/contracts/TokenEscrow.sol",
"BokkyPooBahsDateTimeLibrary/=lib/v4-hooks-public/lib/protocol-fees/lib/BokkyPooBahsDateTimeLibrary/",
"ExcessivelySafeCall/=lib/v4-hooks-public/lib/slipstream/lib/ExcessivelySafeCall/src/",
"aave-address-book/=lib/aave-address-book/src/",
"aave-v3-core/=lib/aave-v3-core/",
"aave-v3-origin/=lib/aave-address-book/lib/aave-v3-origin/",
"aave-v3-periphery/=lib/aave-v3-periphery/contracts/",
"base64-sol/=lib/v4-hooks-public/lib/slipstream/lib/base64/",
"base64/=lib/v4-hooks-public/lib/slipstream/lib/base64/",
"briefcase/=lib/v4-hooks-public/lib/briefcase/src/",
"dao-signer/=lib/v4-hooks-public/lib/protocol-fees/lib/dao-signer/",
"ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
"eas-contracts/=lib/v4-hooks-public/lib/protocol-fees/lib/dao-signer/lib/eas-contracts/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"fluid-contracts-public/=lib/v4-hooks-public/lib/fluid-contracts-public/contracts/",
"forge-gas-snapshot/=lib/v4-hooks-public/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-hooks-public/lib/v4-core/node_modules/hardhat/",
"kontrol-cheatcodes/=lib/v4-hooks-public/lib/protocol-fees/lib/optimism/packages/contracts-bedrock/lib/kontrol-cheatcodes/src/",
"lib-keccak/=lib/v4-hooks-public/lib/protocol-fees/lib/optimism/packages/contracts-bedrock/lib/lib-keccak/contracts/",
"murky/=lib/v4-hooks-public/lib/protocol-fees/lib/murky/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts-v5/=lib/v4-hooks-public/lib/protocol-fees/lib/optimism/packages/contracts-bedrock/lib/openzeppelin-contracts-v5/",
"openzeppelin-contracts/=lib/v4-hooks-public/lib/openzeppelin-contracts/",
"optimism/=lib/v4-hooks-public/lib/protocol-fees/lib/optimism/",
"pancake-v3-contracts/=lib/v4-hooks-public/lib/",
"permit2/=lib/v4-hooks-public/lib/v4-periphery/lib/permit2/",
"protocol-fees/=lib/v4-hooks-public/lib/protocol-fees/",
"safe-contracts/=lib/v4-hooks-public/lib/protocol-fees/lib/optimism/packages/contracts-bedrock/lib/safe-contracts/",
"scripts/libraries/Config.sol=lib/v4-hooks-public/lib/protocol-fees/lib/optimism/packages/contracts-bedrock/scripts/libraries/Config.sol",
"slipstream/=lib/v4-hooks-public/lib/slipstream/",
"solady-v0.0.245/=lib/v4-hooks-public/lib/protocol-fees/lib/optimism/packages/contracts-bedrock/lib/solady-v0.0.245/src/",
"solady/=lib/solady/src/",
"solidity-lib/=lib/v4-hooks-public/lib/slipstream/lib/solidity-lib/contracts/",
"solidity-utils/=lib/aave-address-book/lib/aave-v3-origin/lib/solidity-utils/",
"solmate/=lib/v4-hooks-public/lib/v4-core/lib/solmate/",
"src/AgreementAnchor.sol=lib/v4-hooks-public/lib/protocol-fees/lib/dao-signer/src/AgreementAnchor.sol",
"src/AgreementAnchorFactory.sol=lib/v4-hooks-public/lib/protocol-fees/lib/dao-signer/src/AgreementAnchorFactory.sol",
"src/interfaces/IAgreementAnchorFactory.sol=lib/v4-hooks-public/lib/protocol-fees/lib/dao-signer/src/interfaces/IAgreementAnchorFactory.sol",
"v2-core/=lib/v4-hooks-public/lib/v2-core/contracts/",
"v3-core/=lib/v4-hooks-public/lib/v3-core/",
"v3-periphery/=lib/v4-hooks-public/lib/v3-periphery/contracts/",
"v4-core/=lib/v4-hooks-public/lib/v4-core/src/",
"v4-hooks-public/=lib/v4-hooks-public/",
"v4-periphery/=lib/v4-hooks-public/lib/v4-periphery/",
"nftx/=src/contracts/",
"nftx-interfaces/=src/interfaces/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.