Contract Source Code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {ConsiderationInterface} from "seaport-types/src/interfaces/ConsiderationInterface.sol";
import {OrderType} from "seaport-types/src/lib/ConsiderationEnums.sol";
import {AdvancedOrder, BasicOrderParameters, CriteriaResolver, Execution, Fulfillment, FulfillmentComponent, Order, OrderComponents, OrderParameters} from "seaport-types/src/lib/ConsiderationStructs.sol";
import {ReferenceOrderCombiner} from "./lib/ReferenceOrderCombiner.sol";
import {OrderToExecute} from "./lib/ReferenceConsiderationStructs.sol";
/**
* @title Seaport
* @author 0age
* @custom:coauthor d1ll0n
* @custom:coauthor transmissions11
* @custom:coauthor James Wenzel
* @custom:coauthor Daniel Viau
* @custom:version 1.6-reference
* @notice Consideration is a generalized native token/ERC20/ERC721/ERC1155
* marketplace. It minimizes external calls to the greatest extent
* possible and provides lightweight methods for common routes as well
* as more flexible methods for composing advanced orders or groups of
* orders. Each order contains an arbitrary number of items that may be
* spent (the "offer") along with an arbitrary number of items that must
* be received back by the indicated recipients (the "consideration").
*/
contract Seaport is ConsiderationInterface, ReferenceOrderCombiner {
/**
* @notice Derive and set hashes, reference chainId, and associated domain
* separator during deployment.
*
* @param conduitController A contract that deploys conduits, or proxies
* that may optionally be used to transfer approved
* ERC20/721/1155 tokens.
*/
constructor(
address conduitController
) ReferenceOrderCombiner(conduitController) {}
/**
* @notice Accept native token transfers during execution that may then be
* used to facilitate native token transfers, where any tokens that
* remain will be transferred to the caller. Native tokens are only
* acceptable mid-fulfillment (and not during basic fulfillment).
*/
receive() external payable {
// Ensure the reentrancy guard is currently set to accept native tokens.
_assertAcceptingNativeTokens();
}
/**
* @notice Fulfill an order offering an ERC20, ERC721, or ERC1155 item by
* supplying Ether (or other native tokens), ERC20 tokens, an ERC721
* item, or an ERC1155 item as consideration. Six permutations are
* supported: Native token to ERC721, Native token to ERC1155, ERC20
* to ERC721, ERC20 to ERC1155, ERC721 to ERC20, and ERC1155 to
* ERC20 (with native tokens supplied as msg.value). For an order to
* be eligible for fulfillment via this method, it must contain a
* single offer item (though that item may have a greater amount if
* the item is not an ERC721). An arbitrary number of "additional
* recipients" may also be supplied which will each receive native
* tokens or ERC20 items from the fulfiller as consideration. Refer
* to the documentation for a more comprehensive summary of how to
* utilize with this method and what orders are compatible with it.
*
* @param parameters Additional information on the fulfilled order. Note
* that the offerer and the fulfiller must first approve
* this contract (or their chosen conduit if indicated)
* before any tokens can be transferred. Also note that
* contract recipients of ERC1155 consideration items must
* implement `onERC1155Received` in order to receive those
* items.
*
* @return fulfilled A boolean indicating whether the order has been
* fulfilled.
*/
function fulfillBasicOrder(
BasicOrderParameters calldata parameters
) external payable override nonReentrant(false) returns (bool fulfilled) {
// Validate and fulfill the basic order.
fulfilled = _validateAndFulfillBasicOrder(parameters);
}
/**
* @notice Fulfill an order offering an ERC20, ERC721, or ERC1155 item by
* supplying Ether (or other native tokens), ERC20 tokens, an ERC721
* item, or an ERC1155 item as consideration. Six permutations are
* supported: Native token to ERC721, Native token to ERC1155, ERC20
* to ERC721, ERC20 to ERC1155, ERC721 to ERC20, and ERC1155 to
* ERC20 (with native tokens supplied as msg.value). For an order to
* be eligible for fulfillment via this method, it must contain a
* single offer item (though that item may have a greater amount if
* the item is not an ERC721). An arbitrary number of "additional
* recipients" may also be supplied which will each receive native
* tokens or ERC20 items from the fulfiller as consideration. Refer
* to the documentation for a more comprehensive summary of how to
* utilize with this method and what orders are compatible with it.
* Note that this function costs less gas than `fulfillBasicOrder`
* due to the zero bytes in the function selector (0x00000000) which
* also results in earlier function dispatch.
*
* @param parameters Additional information on the fulfilled order. Note
* that the offerer and the fulfiller must first approve
* this contract (or their chosen conduit if indicated)
* before any tokens can be transferred. Also note that
* contract recipients of ERC1155 consideration items must
* implement `onERC1155Received` in order to receive those
* items.
*
* @return fulfilled A boolean indicating whether the order has been
* fulfilled.
*/
function fulfillBasicOrder_efficient_6GL6yc(
BasicOrderParameters calldata parameters
) external payable override nonReentrant(false) returns (bool fulfilled) {
// Validate and fulfill the basic order.
fulfilled = _validateAndFulfillBasicOrder(parameters);
}
/**
* @notice Fulfill an order with an arbitrary number of items for offer and
* consideration. Note that this function does not support
* criteria-based orders or partial filling of orders (though
* filling the remainder of a partially-filled order is supported).
*
* @param order The order to fulfill. Note that both the
* offerer and the fulfiller must first approve
* this contract (or the corresponding conduit if
* indicated) to transfer any relevant tokens on
* their behalf and that contracts must implement
* `onERC1155Received` to receive ERC1155 tokens
* as consideration.
* @param fulfillerConduitKey A bytes32 value indicating what conduit, if
* any, to source the fulfiller's token approvals
* from. The zero hash signifies that no conduit
* should be used (and direct approvals set on
* Consideration).
*
* @return fulfilled A boolean indicating whether the order has been
* fulfilled.
*/
function fulfillOrder(
Order calldata order,
bytes32 fulfillerConduitKey
)
external
payable
override
nonReentrant(order.parameters.orderType == OrderType.CONTRACT)
returns (bool fulfilled)
{
// Convert order to "advanced" order, then validate and fulfill it.
fulfilled = _validateAndFulfillAdvancedOrder(
_convertOrderToAdvanced(order),
new CriteriaResolver[](0), // No criteria resolvers supplied.
fulfillerConduitKey,
msg.sender
);
}
/**
* @notice Fill an order, fully or partially, with an arbitrary number of
* items for offer and consideration alongside criteria resolvers
* containing specific token identifiers and associated proofs.
*
* @param advancedOrder The order to fulfill along with the fraction
* of the order to attempt to fill. Note that
* both the offerer and the fulfiller must first
* approve this contract (or their proxy if
* indicated by the order) to transfer any
* relevant tokens on their behalf and that
* contracts must implement `onERC1155Received`
* to receive ERC1155 tokens as consideration.
* Also note that all offer and consideration
* components must have no remainder after
* multiplication of the respective amount with
* the supplied fraction for the partial fill to
* be considered valid.
* @param criteriaResolvers An array where each element contains a
* reference to a specific offer or
* consideration, a token identifier, and a proof
* that the supplied token identifier is
* contained in the merkle root held by the item
* in question's criteria element. Note that an
* empty criteria indicates that any
* (transferable) token identifier on the token
* in question is valid and that no associated
* proof needs to be supplied.
* @param fulfillerConduitKey A bytes32 value indicating what conduit, if
* any, to source the fulfiller's token approvals
* from. The zero hash signifies that no conduit
* should be used (and direct approvals set on
* Consideration).
* @param recipient The intended recipient for all received items,
* with `address(0)` indicating that the caller
* should receive the items.
*
* @return fulfilled A boolean indicating whether the order has been
* fulfilled.
*/
function fulfillAdvancedOrder(
AdvancedOrder calldata advancedOrder,
CriteriaResolver[] calldata criteriaResolvers,
bytes32 fulfillerConduitKey,
address recipient
)
external
payable
override
nonReentrant(advancedOrder.parameters.orderType == OrderType.CONTRACT)
returns (bool fulfilled)
{
// Validate and fulfill the order.
fulfilled = _validateAndFulfillAdvancedOrder(
advancedOrder,
criteriaResolvers,
fulfillerConduitKey,
recipient == address(0) ? msg.sender : recipient
);
}
/**
* @notice Attempt to fill a group of orders, each with an arbitrary number
* of items for offer and consideration. Any order that is not
* currently active, has already been fully filled, or has been
* cancelled will be omitted. Remaining offer and consideration
* items will then be aggregated where possible as indicated by the
* supplied offer and consideration component arrays and aggregated
* items will be transferred to the fulfiller or to each intended
* recipient, respectively. Note that a failing item transfer or an
* issue with order formatting will cause the entire batch to fail.
* Note that this function does not support criteria-based orders or
* partial filling of orders (though filling the remainder of a
* partially-filled order is supported).
*
* @param orders The orders to fulfill. Note that both
* the offerer and the fulfiller must first
* approve this contract (or the
* corresponding conduit if indicated) to
* transfer any relevant tokens on their
* behalf and that contracts must implement
* `onERC1155Received` to receive ERC1155
* tokens as consideration.
* @param offerFulfillments An array of FulfillmentComponent arrays
* indicating which offer items to attempt
* to aggregate when preparing executions.
* @param considerationFulfillments An array of FulfillmentComponent arrays
* indicating which consideration items to
* attempt to aggregate when preparing
* executions.
* @param fulfillerConduitKey A bytes32 value indicating what conduit,
* if any, to source the fulfiller's token
* approvals from. The zero hash signifies
* that no conduit should be used (and
* direct approvals set on Consideration).
* @param maximumFulfilled The maximum number of orders to fulfill.
*
* @return availableOrders An array of booleans indicating if each order
* with an index corresponding to the index of the
* returned boolean was fulfillable or not.
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders.
*/
function fulfillAvailableOrders(
Order[] calldata orders,
FulfillmentComponent[][] calldata offerFulfillments,
FulfillmentComponent[][] calldata considerationFulfillments,
bytes32 fulfillerConduitKey,
uint256 maximumFulfilled
)
external
payable
override
nonReentrant(true)
returns (bool[] memory availableOrders, Execution[] memory executions)
{
// Convert orders to "advanced" orders.
AdvancedOrder[] memory advancedOrders = _convertOrdersToAdvanced(
orders
);
// Convert Advanced Orders to Orders To Execute
OrderToExecute[]
memory ordersToExecute = _convertAdvancedToOrdersToExecute(
advancedOrders
);
// Fulfill all available orders.
return
_fulfillAvailableAdvancedOrders(
advancedOrders,
ordersToExecute,
new CriteriaResolver[](0), // No criteria resolvers supplied.
offerFulfillments,
considerationFulfillments,
fulfillerConduitKey,
msg.sender,
maximumFulfilled
);
}
/**
* @notice Attempt to fill a group of orders, fully or partially, with an
* arbitrary number of items for offer and consideration per order
* alongside criteria resolvers containing specific token
* identifiers and associated proofs. Any order that is not
* currently active, has already been fully filled, or has been
* cancelled will be omitted. Remaining offer and consideration
* items will then be aggregated where possible as indicated by the
* supplied offer and consideration component arrays and aggregated
* items will be transferred to the fulfiller or to each intended
* recipient, respectively. Note that a failing item transfer or an
* issue with order formatting will cause the entire batch to fail.
*
* @param advancedOrders The orders to fulfill along with the
* fraction of those orders to attempt to
* fill. Note that both the offerer and the
* fulfiller must first approve this
* contract (or their proxy if indicated by
* the order) to transfer any relevant
* tokens on their behalf and that
* contracts must implement
* `onERC1155Received` in order to receive
* ERC1155 tokens as consideration. Also
* note that all offer and consideration
* components must have no remainder after
* multiplication of the respective amount
* with the supplied fraction for an
* order's partial fill amount to be
* considered valid.
* @param criteriaResolvers An array where each element contains a
* reference to a specific offer or
* consideration, a token identifier, and a
* proof that the supplied token identifier
* is contained in the merkle root held by
* the item in question's criteria element.
* Note that an empty criteria indicates
* that any (transferable) token
* identifier on the token in question is
* valid and that no associated proof needs
* to be supplied.
* @param offerFulfillments An array of FulfillmentComponent arrays
* indicating which offer items to attempt
* to aggregate when preparing executions.
* @param considerationFulfillments An array of FulfillmentComponent arrays
* indicating which consideration items to
* attempt to aggregate when preparing
* executions.
* @param fulfillerConduitKey A bytes32 value indicating what conduit,
* if any, to source the fulfiller's token
* approvals from. The zero hash signifies
* that no conduit should be used (and
* direct approvals set on Consideration).
* @param maximumFulfilled The maximum number of orders to fulfill.
*
* * @return availableOrders An array of booleans indicating if each order
* with an index corresponding to the index of the
* returned boolean was fulfillable or not.
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders.
*/
function fulfillAvailableAdvancedOrders(
AdvancedOrder[] memory advancedOrders,
CriteriaResolver[] calldata criteriaResolvers,
FulfillmentComponent[][] calldata offerFulfillments,
FulfillmentComponent[][] calldata considerationFulfillments,
bytes32 fulfillerConduitKey,
address recipient,
uint256 maximumFulfilled
)
external
payable
override
nonReentrant(true)
returns (bool[] memory availableOrders, Execution[] memory executions)
{
// Convert Advanced Orders to Orders to Execute
OrderToExecute[]
memory ordersToExecute = _convertAdvancedToOrdersToExecute(
advancedOrders
);
// Fulfill all available orders.
return
_fulfillAvailableAdvancedOrders(
advancedOrders,
ordersToExecute,
criteriaResolvers,
offerFulfillments,
considerationFulfillments,
fulfillerConduitKey,
recipient == address(0) ? msg.sender : recipient,
maximumFulfilled
);
}
/**
* @notice Match an arbitrary number of orders, each with an arbitrary
* number of items for offer and consideration along with a set of
* fulfillments allocating offer components to consideration
* components. Note that this function does not support
* criteria-based or partial filling of orders (though filling the
* remainder of a partially-filled order is supported).
*
* @param orders The orders to match. Note that both the offerer and
* fulfiller on each order must first approve this
* contract (or their conduit if indicated by the
* order) to transfer any relevant tokens on their
* behalf and each consideration recipient must
* implement `onERC1155Received` in order to receive
* ERC1155 tokens.
* @param fulfillments An array of elements allocating offer components to
* consideration components. Note that each
* consideration component must be fully met in order
* for the match operation to be valid.
*
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders. Note that unspent offer item amounts or
* native tokens will not be reflected as part of this
* array.
*/
function matchOrders(
Order[] calldata orders,
Fulfillment[] calldata fulfillments
)
external
payable
override
nonReentrant(true)
returns (Execution[] memory executions)
{
// Convert to advanced, validate, and match orders using fulfillments.
return
_matchAdvancedOrders(
_convertOrdersToAdvanced(orders),
new CriteriaResolver[](0), // No criteria resolvers supplied.
fulfillments,
msg.sender
);
}
/**
* @notice Match an arbitrary number of full or partial orders, each with an
* arbitrary number of items for offer and consideration, supplying
* criteria resolvers containing specific token identifiers and
* associated proofs as well as fulfillments allocating offer
* components to consideration components.
*
* @param advancedOrders The advanced orders to match. Note that both the
* offerer and fulfiller on each order must first
* approve this contract (or their proxy if
* indicated by the order) to transfer any relevant
* tokens on their behalf and each consideration
* recipient must implement `onERC1155Received` in
* order to receive ERC1155 tokens. Also note that
* the offer and consideration components for each
* order must have no remainder after multiplying
* the respective amount with the supplied fraction
* in order for the group of partial fills to be
* considered valid.
* @param criteriaResolvers An array where each element contains a reference
* to a specific order as well as that order's
* offer or consideration, a token identifier, and
* a proof that the supplied token identifier is
* contained in the order's merkle root. Note that
* an empty root indicates that any (transferable)
* token identifier is valid and that no associated
* proof needs to be supplied.
* @param fulfillments An array of elements allocating offer components
* to consideration components. Note that each
* consideration component must be fully met in
* order for the match operation to be valid.
* @param recipient The intended recipient for all unspent offer
* item amounts, or the caller if the null address
* is supplied.
*
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders. Note that unspent offer item amounts or
* native tokens will not be reflected as part of this
* array.
*/
function matchAdvancedOrders(
AdvancedOrder[] memory advancedOrders,
CriteriaResolver[] calldata criteriaResolvers,
Fulfillment[] calldata fulfillments,
address recipient
)
external
payable
override
nonReentrant(true)
returns (Execution[] memory executions)
{
// Validate and match the advanced orders using supplied fulfillments.
return
_matchAdvancedOrders(
advancedOrders,
criteriaResolvers,
fulfillments,
recipient == address(0) ? msg.sender : recipient
);
}
/**
* @notice Cancel an arbitrary number of orders. Note that only the offerer
* or the zone of a given order may cancel it.
*
* @param orders The orders to cancel.
*
* @return cancelled A boolean indicating whether the supplied orders have
* been successfully cancelled.
*/
function cancel(
OrderComponents[] calldata orders
) external override notEntered returns (bool cancelled) {
// Cancel the orders.
cancelled = _cancel(orders);
}
/**
* @notice Validate an arbitrary number of orders, thereby registering them
* as valid and allowing the fulfiller to skip verification. Note
* that anyone can validate a signed order but only the offerer can
* validate an order without supplying a signature.
*
* @param orders The orders to validate.
*
* @return validated A boolean indicating whether the supplied orders have
* been successfully validated.
*/
function validate(
Order[] calldata orders
) external override notEntered returns (bool validated) {
// Validate the orders.
validated = _validate(orders);
}
/**
* @notice Cancel all orders from a given offerer with a given zone in bulk
* by incrementing a counter. Note that only the offerer may
* increment the counter.
*
* @return newCounter The new counter.
*/
function incrementCounter()
external
override
notEntered
returns (uint256 newCounter)
{
// Increment current counter for the supplied offerer.
newCounter = _incrementCounter();
}
/**
* @notice Retrieve the order hash for a given order.
*
* @param order The components of the order.
*
* @return orderHash the order hash.
*/
function getOrderHash(
OrderComponents calldata order
) external view override returns (bytes32 orderHash) {
// Derive order hash by supplying order parameters along with the
// counter.
orderHash = _deriveOrderHash(
OrderParameters(
order.offerer,
order.zone,
order.offer,
order.consideration,
order.orderType,
order.startTime,
order.endTime,
order.zoneHash,
order.salt,
order.conduitKey,
order.consideration.length
),
order.counter
);
}
/**
* @notice Retrieve the status of a given order by hash, including whether
* the order has been cancelled or validated and the fraction of the
* order that has been filled. Since the _orderStatus[orderHash]
* does not get set for contract orders, getOrderStatus will always
* return (false, false, 0, 0) for those hashes. Note that this
* function is susceptible to view reentrancy and so should be used
* with care when calling from other contracts.
*
* @param orderHash The order hash in question.
*
* @return isValidated A boolean indicating whether the order in question
* has been validated (i.e. previously approved or
* partially filled).
* @return isCancelled A boolean indicating whether the order in question
* has been cancelled.
* @return totalFilled The total portion of the order that has been filled
* (i.e. the "numerator").
* @return totalSize The total size of the order that is either filled or
* unfilled (i.e. the "denominator").
*/
function getOrderStatus(
bytes32 orderHash
)
external
view
override
returns (
bool isValidated,
bool isCancelled,
uint256 totalFilled,
uint256 totalSize
)
{
// Retrieve the order status using the order hash.
return _getOrderStatus(orderHash);
}
/**
* @notice Retrieve the current counter for a given offerer.
*
* @param offerer The offerer in question.
*
* @return counter The current counter.
*/
function getCounter(
address offerer
) external view override returns (uint256 counter) {
// Return the counter for the supplied offerer.
counter = _getCounter(offerer);
}
/**
* @notice Retrieve configuration information for this contract.
*
* @return version The contract version.
* @return domainSeparator The domain separator for this contract.
* @return conduitController The conduit Controller set for this contract.
*/
function information()
external
view
override
returns (
string memory version,
bytes32 domainSeparator,
address conduitController
)
{
// Return the information for this contract.
return _information();
}
/**
* @dev Gets the contract offerer nonce for the specified contract offerer.
* Note that this function is susceptible to view reentrancy and so
* should be used with care when calling from other contracts.
*
* @param contractOfferer The contract offerer for which to get the nonce.
*
* @return nonce The contract offerer nonce.
*/
function getContractOffererNonce(
address contractOfferer
) external view override returns (uint256 nonce) {
nonce = _contractNonces[contractOfferer];
}
/**
* @notice Retrieve the name of this contract.
*
* @return contractName The name of this contract.
*/
function name()
external
pure
override
returns (string memory contractName)
{
// Return the name of the contract.
contractName = _name();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ItemType,
OrderType
} from "seaport-types/src/lib/ConsiderationEnums.sol";
import {
ReceivedItem,
SpentItem
} from "seaport-types/src/lib/ConsiderationStructs.sol";
import {
ConduitTransfer
} from "seaport-types/src/conduit/lib/ConduitStructs.sol";
// This file should only be used by the Reference Implementation
/**
* @dev A struct used to hold the numerator and denominator of an order in-memory
* during validation, before it is written to storage when updating order
* status.
*/
struct StoredFractions {
uint256 storedNumerator;
uint256 storedDenominator;
}
/**
* @dev An intermediate struct used to hold information about an order after
* validation to prepare for execution.
*/
struct OrderValidation {
bytes32 orderHash;
uint256 newNumerator;
uint256 newDenominator;
OrderToExecute orderToExecute;
}
/**
* @dev A struct used to hold the parameters used to validate an order.
*/
struct OrderValidationParams {
bool revertOnInvalid;
uint256 maximumFulfilled;
address recipient;
}
/**
* @dev A struct used to hold Consideration Indexes and Fulfillment validity.
*/
struct ConsiderationItemIndicesAndValidity {
uint256 orderIndex;
uint256 itemIndex;
bool invalidFulfillment;
bool missingItemAmount;
}
/**
* @dev A struct used to hold all ItemTypes/Token of a Basic Order Fulfillment
* used in _prepareBasicFulfillmentFromCalldata
*/
struct FulfillmentItemTypes {
OrderType orderType;
ItemType receivedItemType;
ItemType additionalRecipientsItemType;
address additionalRecipientsToken;
ItemType offeredItemType;
}
/**
* @dev A struct used to hold all the hashes of a Basic Order Fulfillment
* used in _prepareBasicFulfillmentFromCalldata and _hashOrder
*/
struct BasicFulfillmentHashes {
bytes32 typeHash;
bytes32 orderHash;
bytes32 offerItemsHash;
bytes32[] considerationHashes;
bytes32 receivedItemsHash;
bytes32 receivedItemHash;
bytes32 offerItemHash;
}
/**
* @dev A struct that is an explicit version of advancedOrders without
* memory optimization, that provides an array of spentItems
* and receivedItems for fulfillment and event emission.
*/
struct OrderToExecute {
address offerer;
SpentItem[] spentItems; // Offer
ReceivedItem[] receivedItems; // Consideration
bytes32 conduitKey;
uint120 numerator;
uint256[] spentItemOriginalAmounts;
uint256[] receivedItemOriginalAmounts;
}
/**
* @dev A struct containing the data used to apply a
* fraction to an order.
*/
struct FractionData {
uint256 numerator; // The portion of the order that should be filled.
uint256 denominator; // The total size of the order
bytes32 fulfillerConduitKey; // The fulfiller's conduit key.
uint256 startTime; // The start time of the order.
uint256 endTime; // The end time of the order.
}
/**
* @dev A struct containing conduit transfer data and its
* corresponding conduitKey.
*/
struct AccumulatorStruct {
bytes32 conduitKey;
ConduitTransfer[] transfers;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ItemType,
OrderType,
Side
} from "seaport-types/src/lib/ConsiderationEnums.sol";
import {
AdvancedOrder,
ConsiderationItem,
CriteriaResolver,
Execution,
Fulfillment,
FulfillmentComponent,
OfferItem,
OrderParameters,
ReceivedItem,
SpentItem
} from "seaport-types/src/lib/ConsiderationStructs.sol";
import {
SeaportInterface
} from "seaport-types/src/interfaces/SeaportInterface.sol";
import {
AccumulatorStruct,
OrderToExecute,
StoredFractions,
OrderValidation,
OrderValidationParams
} from "./ReferenceConsiderationStructs.sol";
import { ReferenceOrderFulfiller } from "./ReferenceOrderFulfiller.sol";
import { ReferenceFulfillmentApplier } from "./ReferenceFulfillmentApplier.sol";
/**
* @title OrderCombiner
* @author 0age
* @notice OrderCombiner contains logic for fulfilling combinations of orders,
* either by matching offer items to consideration items or by
* fulfilling orders where available.
*/
contract ReferenceOrderCombiner is
ReferenceOrderFulfiller,
ReferenceFulfillmentApplier
{
/**
* @dev Derive and set hashes, reference chainId, and associated domain
* separator during deployment.
*
* @param conduitController A contract that deploys conduits, or proxies
* that may optionally be used to transfer approved
* ERC20/721/1155 tokens.
*/
constructor(
address conduitController
) ReferenceOrderFulfiller(conduitController) {}
/**
* @notice Internal function to attempt to fill a group of orders, fully or
* partially, with an arbitrary number of items for offer and
* consideration per order alongside criteria resolvers containing
* specific token identifiers and associated proofs. Any order that
* is not currently active, has already been fully filled, or has
* been cancelled will be omitted. Remaining offer and consideration
* items will then be aggregated where possible as indicated by the
* supplied offer and consideration component arrays and aggregated
* items will be transferred to the fulfiller or to each intended
* recipient, respectively. Note that a failing item transfer or an
* issue with order formatting will cause the entire batch to fail.
*
* @param advancedOrders The orders to fulfill along with the
* fraction of those orders to attempt to
* fill. Note that both the offerer and the
* fulfiller must first approve this
* contract (or their proxy if indicated by
* the order) to transfer any relevant
* tokens on their behalf and that
* contracts must implement
* `onERC1155Received` in order to receive
* ERC1155 tokens as consideration. Also
* note that all offer and consideration
* components must have no remainder after
* multiplication of the respective amount
* with the supplied fraction for an
* order's partial fill amount to be
* considered valid.
*
* @param ordersToExecute The orders to execute. This is an
* explicit version of advancedOrders
* without memory optimization, that
* provides an array of spentItems and
* receivedItems for fulfillment and
* event emission.
*
* @param criteriaResolvers An array where each element contains a
* reference to a specific offer or
* consideration, a token identifier, and a
* proof that the supplied token identifier
* is contained in the merkle root held by
* the item in question's criteria element.
* Note that an empty criteria indicates
* that any (transferable) token
* identifier on the token in question is
* valid and that no associated proof needs
* to be supplied.
* @param offerFulfillments An array of FulfillmentComponent arrays
* indicating which offer items to attempt
* to aggregate when preparing executions.
* @param considerationFulfillments An array of FulfillmentComponent arrays
* indicating which consideration items to
* attempt to aggregate when preparing
* executions.
* @param fulfillerConduitKey A bytes32 value indicating what conduit,
* if any, to source the fulfiller's token
* approvals from. The zero hash signifies
* that no conduit should be used (and
* direct approvals set on Consideration).
* @param recipient The intended recipient for all received
* items.
* @param maximumFulfilled The maximum number of orders to fulfill.
*
* @return availableOrders An array of booleans indicating if each
* order with an index corresponding to the
* index of the returned boolean was
* fulfillable or not.
* @return executions An array of elements indicating the
* sequence of transfers performed as part
* of matching the given orders.
*/
function _fulfillAvailableAdvancedOrders(
AdvancedOrder[] memory advancedOrders,
OrderToExecute[] memory ordersToExecute,
CriteriaResolver[] memory criteriaResolvers,
FulfillmentComponent[][] calldata offerFulfillments,
FulfillmentComponent[][] calldata considerationFulfillments,
bytes32 fulfillerConduitKey,
address recipient,
uint256 maximumFulfilled
)
internal
returns (bool[] memory availableOrders, Execution[] memory executions)
{
// Validate orders, apply amounts, & determine if they use conduits.
(
bytes32[] memory orderHashes,
bool containsNonOpen
) = _validateOrdersAndPrepareToFulfill(
advancedOrders,
ordersToExecute,
criteriaResolvers,
OrderValidationParams(
false, // Signifies that invalid orders should NOT revert.
maximumFulfilled,
recipient
)
);
// Execute transfers.
(availableOrders, executions) = _executeAvailableFulfillments(
advancedOrders,
ordersToExecute,
offerFulfillments,
considerationFulfillments,
fulfillerConduitKey,
recipient,
orderHashes,
containsNonOpen
);
// Return order fulfillment details and executions.
return (availableOrders, executions);
}
/**
* @dev Internal function to validate a group of orders, update their
* statuses, reduce amounts by their previously filled fractions, apply
* criteria resolvers, and emit OrderFulfilled events.
*
* @param advancedOrders The advanced orders to validate and reduce by
* their previously filled amounts.
* @param ordersToExecute The orders to validate and execute.
* @param criteriaResolvers An array where each element contains a reference
* to a specific order as well as that order's
* offer or consideration, a token identifier, and
* a proof that the supplied token identifier is
* contained in the order's merkle root. Note that
* a root of zero indicates that any transferable
* token identifier is valid and that no proof
* needs to be supplied.
* @param orderValidationParams Various order validation params.
*
* @return orderHashes The hashes of the orders being fulfilled.
* @return containsNonOpen A boolean indicating whether any restricted or
* contract orders are present within the provided
* array of advanced orders.
*/
function _validateOrdersAndPrepareToFulfill(
AdvancedOrder[] memory advancedOrders,
OrderToExecute[] memory ordersToExecute,
CriteriaResolver[] memory criteriaResolvers,
OrderValidationParams memory orderValidationParams
) internal returns (bytes32[] memory orderHashes, bool containsNonOpen) {
// Track the order hash for each order being fulfilled.
orderHashes = new bytes32[](advancedOrders.length);
// Declare a variable for tracking whether native offer items are
// present on orders that are not contract orders.
bool anyNativeOfferItemsOnNonContractOrders;
StoredFractions[] memory storedFractions = new StoredFractions[](
advancedOrders.length
);
// Iterate over each order.
for (uint256 i = 0; i < advancedOrders.length; ++i) {
// Retrieve the current order.
AdvancedOrder memory advancedOrder = advancedOrders[i];
// Validate the order and determine fraction to fill.
OrderValidation memory orderValidation = _validateOrder(
advancedOrder,
orderValidationParams.revertOnInvalid
);
// Do not track hash or adjust prices if order is not fulfilled.
if (orderValidation.newNumerator == 0) {
// Mark fill fraction as zero if the order is not fulfilled.
advancedOrder.numerator = 0;
// Mark fill fraction as zero as the order will not be used.
orderValidation.orderToExecute.numerator = 0;
ordersToExecute[i] = orderValidation.orderToExecute;
// Continue iterating through the remaining orders.
continue;
}
// Otherwise, track the order hash in question.
orderHashes[i] = orderValidation.orderHash;
// Store the numerator and denominator for the order status.
storedFractions[i] = StoredFractions({
storedNumerator: orderValidation.newNumerator,
storedDenominator: orderValidation.newDenominator
});
{
// Retrieve array of offer items for the order in question.
OfferItem[] memory offer = advancedOrder.parameters.offer;
// Determine the order type, used to check for eligibility for
// native token offer items as well as for the presence of
// restricted and contract orders (or non-open orders).
OrderType orderType = advancedOrder.parameters.orderType;
{
bool isNonContractOrder = orderType != OrderType.CONTRACT;
bool isNonOpenOrder = orderType != OrderType.FULL_OPEN &&
orderType != OrderType.PARTIAL_OPEN;
if (containsNonOpen == true || isNonOpenOrder == true) {
containsNonOpen = true;
}
// Iterate over each offer item on the order.
for (uint256 j = 0; j < offer.length; ++j) {
// Retrieve the offer item.
OfferItem memory offerItem = offer[j];
// Determine if there are any native offer items on
// non-contract orders.
anyNativeOfferItemsOnNonContractOrders =
anyNativeOfferItemsOnNonContractOrders ||
(offerItem.itemType == ItemType.NATIVE &&
isNonContractOrder);
// Apply order fill fraction to offer item end amount.
uint256 endAmount = _getFraction(
orderValidation.newNumerator,
orderValidation.newDenominator,
offerItem.endAmount
);
// Reuse same fraction if start & end amounts are equal.
if (offerItem.startAmount == offerItem.endAmount) {
// Apply derived amount to both start & end amount.
offerItem.startAmount = endAmount;
} else {
// Apply order fill fraction to item start amount.
offerItem.startAmount = _getFraction(
orderValidation.newNumerator,
orderValidation.newDenominator,
offerItem.startAmount
);
}
// Update end amount in memory to match derived amount.
offerItem.endAmount = endAmount;
// Adjust offer amount using current time; round down.
offerItem.startAmount = _locateCurrentAmount(
offerItem.startAmount,
offerItem.endAmount,
advancedOrder.parameters.startTime,
advancedOrder.parameters.endTime,
false // Round down.
);
// Modify the OrderToExecute Spent Item Amount.
orderValidation
.orderToExecute
.spentItems[j]
.amount = offerItem.startAmount;
// Modify the OrderToExecute Spent Item Original amount.
orderValidation.orderToExecute.spentItemOriginalAmounts[
j
] = (offerItem.startAmount);
}
}
{
// Get array of consideration items for order in question.
ConsiderationItem[] memory consideration = (
advancedOrder.parameters.consideration
);
// Iterate over each consideration item on the order.
for (uint256 j = 0; j < consideration.length; ++j) {
// Retrieve the consideration item.
ConsiderationItem memory considerationItem = (
consideration[j]
);
// Apply fraction to consideration item end amount.
uint256 endAmount = _getFraction(
orderValidation.newNumerator,
orderValidation.newDenominator,
considerationItem.endAmount
);
// Reuse same fraction if start & end amounts are equal.
if (
considerationItem.startAmount ==
(considerationItem.endAmount)
) {
// Apply derived amount to both start & end amount.
considerationItem.startAmount = endAmount;
} else {
// Apply fraction to item start amount.
considerationItem.startAmount = _getFraction(
orderValidation.newNumerator,
orderValidation.newDenominator,
considerationItem.startAmount
);
}
uint256 currentAmount = (
_locateCurrentAmount(
considerationItem.startAmount,
endAmount,
advancedOrder.parameters.startTime,
advancedOrder.parameters.endTime,
true // round up
)
);
considerationItem.startAmount = currentAmount;
// Modify the OrderToExecute Received item amount.
orderValidation
.orderToExecute
.receivedItems[j]
.amount = considerationItem.startAmount;
// Modify OrderToExecute Received item original amount.
orderValidation
.orderToExecute
.receivedItemOriginalAmounts[j] = (
considerationItem.startAmount
);
}
}
}
ordersToExecute[i] = orderValidation.orderToExecute;
}
if (
anyNativeOfferItemsOnNonContractOrders &&
(msg.sig != SeaportInterface.matchAdvancedOrders.selector &&
msg.sig != SeaportInterface.matchOrders.selector)
) {
revert InvalidNativeOfferItem();
}
// Apply criteria resolvers to each order as applicable.
_applyCriteriaResolvers(
advancedOrders,
ordersToExecute,
criteriaResolvers
);
bool someOrderAvailable;
// Iterate over each order to check authorization status (for restricted
// orders), generate orders (for contract orders), and emit events (for
// all available orders) signifying that they have been fulfilled.
for (uint256 i = 0; i < advancedOrders.length; ++i) {
// Do not emit an event if no order hash is present.
if (orderHashes[i] == bytes32(0)) {
continue;
}
// Determine if max number orders have already been fulfilled.
if (orderValidationParams.maximumFulfilled == 0) {
orderHashes[i] = bytes32(0);
ordersToExecute[i].numerator = 0;
// Continue iterating through the remaining orders.
continue;
}
// Retrieve parameters for the order in question.
OrderParameters memory orderParameters = (
advancedOrders[i].parameters
);
// Ensure restricted orders have valid submitter or pass zone check.
(
bool valid /* bool checked */,
) = _checkRestrictedAdvancedOrderAuthorization(
advancedOrders[i],
ordersToExecute[i],
_shorten(orderHashes, i),
orderHashes[i],
orderValidationParams.revertOnInvalid
);
if (!valid) {
orderHashes[i] = bytes32(0);
ordersToExecute[i].numerator = 0;
continue;
}
// Update status if the order is still valid or skip if not checked
if (orderParameters.orderType != OrderType.CONTRACT) {
if (
!_updateStatus(
orderHashes[i],
storedFractions[i].storedNumerator,
storedFractions[i].storedDenominator,
_revertOnFailedUpdate(
orderParameters,
orderValidationParams.revertOnInvalid
)
)
) {
orderHashes[i] = bytes32(0);
ordersToExecute[i].numerator = 0;
continue;
}
} else {
bytes32 orderHash = _getGeneratedOrder(
ordersToExecute[i],
orderParameters,
advancedOrders[i].extraData,
orderValidationParams.revertOnInvalid
);
orderHashes[i] = orderHash;
if (orderHash == bytes32(0)) {
ordersToExecute[i].numerator = 0;
continue;
}
}
// Decrement the number of fulfilled orders.
orderValidationParams.maximumFulfilled--;
// Get the array of spentItems from the orderToExecute struct.
SpentItem[] memory spentItems = ordersToExecute[i].spentItems;
// Get the array of spent receivedItems from the
// orderToExecute struct.
ReceivedItem[] memory receivedItems = (
ordersToExecute[i].receivedItems
);
// Emit an event signifying that the order has been fulfilled.
emit OrderFulfilled(
orderHashes[i],
orderParameters.offerer,
orderParameters.zone,
orderValidationParams.recipient,
spentItems,
receivedItems
);
someOrderAvailable = true;
}
// Revert if no orders are available.
if (!someOrderAvailable) {
revert NoSpecifiedOrdersAvailable();
}
}
function _shorten(
bytes32[] memory orderHashes,
uint256 index
) internal pure returns (bytes32[] memory) {
bytes32[] memory shortened = new bytes32[](index);
for (uint256 i = 0; i < index; i++) {
shortened[i] = orderHashes[i];
}
return shortened;
}
/**
* @dev Internal function to fulfill a group of validated orders, fully or
* partially, with an arbitrary number of items for offer and
* consideration per order and to execute transfers. Any order that is
* not currently active, has already been fully filled, or has been
* cancelled will be omitted. Remaining offer and consideration items
* will then be aggregated where possible as indicated by the supplied
* offer and consideration component arrays and aggregated items will
* be transferred to the fulfiller or to each intended recipient,
* respectively. Note that a failing item transfer or an issue with
* order formatting will cause the entire batch to fail.
*
* @param ordersToExecute The orders to execute. This is an
* explicit version of advancedOrders
* without memory optimization, that
* provides an array of spentItems and
* receivedItems for fulfillment and
* event emission.
* Note that both the offerer and the
* fulfiller must first approve this
* contract (or the conduit if indicated
* by the order) to transfer any relevant
* tokens on their behalf and that
* contracts must implement
* `onERC1155Received` in order to receive
* ERC1155 tokens as consideration. Also
* note that all offer and consideration
* components must have no remainder after
* multiplication of the respective amount
* with the supplied fraction for an
* order's partial fill amount to be
* considered valid.
* @param offerFulfillments An array of FulfillmentComponent arrays
* indicating which offer items to attempt
* to aggregate when preparing executions.
* @param considerationFulfillments An array of FulfillmentComponent arrays
* indicating which consideration items to
* attempt to aggregate when preparing
* executions.
* @param fulfillerConduitKey A bytes32 value indicating what conduit,
* if any, to source the fulfiller's token
* approvals from. The zero hash signifies
* that no conduit should be used (and
* direct approvals set on Consideration).
* @param recipient The intended recipient for all received
* items.
* @param orderHashes An array of order hashes for each order.
* @param containsNonOpen A boolean indicating whether any restricted or
* contract orders are present within the provided
* array of advanced orders.
*
* @return availableOrders An array of booleans indicating if each
* order with an index corresponding to the
* index of the returned boolean was
* fulfillable or not.
* @return executions An array of elements indicating the
* sequence of transfers performed as part
* of matching the given orders.
*/
function _executeAvailableFulfillments(
AdvancedOrder[] memory advancedOrders,
OrderToExecute[] memory ordersToExecute,
FulfillmentComponent[][] memory offerFulfillments,
FulfillmentComponent[][] memory considerationFulfillments,
bytes32 fulfillerConduitKey,
address recipient,
bytes32[] memory orderHashes,
bool containsNonOpen
)
internal
returns (bool[] memory availableOrders, Execution[] memory executions)
{
// Retrieve length of offer fulfillments array and place on the stack.
uint256 totalOfferFulfillments = offerFulfillments.length;
// Retrieve length of consideration fulfillments array & place on stack.
uint256 totalConsiderationFulfillments = (
considerationFulfillments.length
);
// Allocate an execution for each offer and consideration fulfillment.
executions = new Execution[](
totalOfferFulfillments + totalConsiderationFulfillments
);
// Iterate over each offer fulfillment.
for (uint256 i = 0; i < totalOfferFulfillments; ++i) {
// Derive aggregated execution corresponding with fulfillment and
// assign the execution to the executions array.
executions[i] = _aggregateAvailable(
ordersToExecute,
Side.OFFER,
offerFulfillments[i],
fulfillerConduitKey,
recipient
);
}
// Iterate over each consideration fulfillment.
for (uint256 i = 0; i < totalConsiderationFulfillments; ++i) {
// Derive aggregated execution corresponding with fulfillment and
// assign the execution to the executions array.
executions[i + totalOfferFulfillments] = _aggregateAvailable(
ordersToExecute,
Side.CONSIDERATION,
considerationFulfillments[i],
fulfillerConduitKey,
address(0) // unused
);
}
// Perform final checks and compress executions into standard and batch.
availableOrders = _performFinalChecksAndExecuteOrders(
advancedOrders,
ordersToExecute,
executions,
orderHashes,
recipient,
containsNonOpen
);
return (availableOrders, executions);
}
/**
* @dev Internal function to perform a final check that each consideration
* item for an arbitrary number of fulfilled orders has been met and to
* trigger associated executions, transferring the respective items.
*
* @param ordersToExecute The orders to check and perform executions.
* @param executions An array of uncompressed elements indicating
* the sequence of transfers to perform when
* fulfilling the given orders.
*
* @param executions An array of elements indicating the sequence of
* transfers to perform when fulfilling the given
* orders.
* @param orderHashes An array of order hashes for each order.
* @param containsNonOpen A boolean indicating whether any restricted or
* contract orders are present within the provided
* array of advanced orders.
*
* @return availableOrders An array of booleans indicating if each order
* with an index corresponding to the index of the
* returned boolean was fulfillable or not.
*/
function _performFinalChecksAndExecuteOrders(
AdvancedOrder[] memory advancedOrders,
OrderToExecute[] memory ordersToExecute,
Execution[] memory executions,
bytes32[] memory orderHashes,
address recipient,
bool containsNonOpen
) internal returns (bool[] memory availableOrders) {
// Retrieve the length of the advanced orders array and place on stack.
uint256 totalOrders = advancedOrders.length;
// Initialize array for tracking available orders.
availableOrders = new bool[](totalOrders);
// Create the accumulator struct.
AccumulatorStruct memory accumulatorStruct;
{
// Iterate over each execution.
for (uint256 i = 0; i < executions.length; ++i) {
// Retrieve the execution and the associated received item.
Execution memory execution = executions[i];
ReceivedItem memory item = execution.item;
// Skip transfers if the execution amount is zero.
if (item.amount == 0) {
continue;
}
// If execution transfers native tokens, reduce value available.
if (item.itemType == ItemType.NATIVE) {
// Ensure that sufficient native tokens are still available.
if (item.amount > address(this).balance) {
revert InsufficientNativeTokensSupplied();
}
}
// Transfer the item specified by the execution.
_transfer(
item,
execution.offerer,
execution.conduitKey,
accumulatorStruct
);
}
}
// Duplicate recipient onto stack to avoid stack-too-deep.
address _recipient = recipient;
// Iterate over orders to ensure all consideration items are met.
for (uint256 i = 0; i < ordersToExecute.length; ++i) {
// Retrieve the order in question.
OrderToExecute memory orderToExecute = ordersToExecute[i];
// Skip consideration item checks for order if not fulfilled.
if (orderToExecute.numerator == 0) {
// Note: orders do not need to be marked as unavailable as a
// new memory region has been allocated. Review carefully if
// altering compiler version or managing memory manually.
continue;
}
// Mark the order as available.
availableOrders[i] = true;
// Retrieve the original order in question.
AdvancedOrder memory advancedOrder = advancedOrders[i];
// Retrieve the order parameters.
OrderParameters memory parameters = advancedOrder.parameters;
{
// Retrieve offer items.
SpentItem[] memory offer = orderToExecute.spentItems;
// Read length of offer array & place on the stack.
uint256 totalOfferItems = offer.length;
// Iterate over each offer item to restore it.
for (uint256 j = 0; j < totalOfferItems; ++j) {
SpentItem memory offerSpentItem = offer[j];
// Retrieve remaining amount on the offer item.
uint256 unspentAmount = offerSpentItem.amount;
// Retrieve original amount on the offer item.
uint256 originalAmount = (
orderToExecute.spentItemOriginalAmounts[j]
);
// Transfer to recipient if unspent amount is not zero.
// Note that the transfer will not be reflected in the
// executions array.
if (unspentAmount != 0) {
_transfer(
_convertSpentItemToReceivedItemWithRecipient(
offerSpentItem,
_recipient
),
parameters.offerer,
parameters.conduitKey,
accumulatorStruct
);
}
// Restore original amount on the offer item.
offerSpentItem.amount = originalAmount;
}
}
{
// Retrieve consideration items to ensure they are fulfilled.
ReceivedItem[] memory consideration = (
orderToExecute.receivedItems
);
// Iterate over each consideration item to ensure it is met.
for (uint256 j = 0; j < consideration.length; ++j) {
// Retrieve remaining amount on the consideration item.
uint256 unmetAmount = consideration[j].amount;
// Revert if the remaining amount is not zero.
if (unmetAmount != 0) {
revert ConsiderationNotMet(i, j, unmetAmount);
}
// Restore original amount.
consideration[j].amount = (
orderToExecute.receivedItemOriginalAmounts[j]
);
}
}
}
// Trigger any remaining accumulated transfers via call to the
// conduit.
_triggerIfArmed(accumulatorStruct);
// If any native token remains after fulfillments, return it to the
// caller.
if (address(this).balance != 0) {
_transferNativeTokens(payable(msg.sender), address(this).balance);
}
// If any restricted or contract orders are present in the group of
// orders being fulfilled, perform any validateOrder or ratifyOrder
// calls after all executions and related transfers are complete.
if (containsNonOpen) {
// Iterate over orders to ensure all consideration items are met.
for (uint256 i = 0; i < ordersToExecute.length; ++i) {
// Retrieve the order in question.
OrderToExecute memory orderToExecute = ordersToExecute[i];
// Skip consideration item checks for order if not fulfilled.
if (orderToExecute.numerator == 0) {
continue;
}
// Retrieve the original order in question.
AdvancedOrder memory advancedOrder = advancedOrders[i];
// Ensure restricted orders have valid submitter or pass check.
_assertRestrictedAdvancedOrderValidity(
advancedOrder,
orderToExecute,
orderHashes,
orderHashes[i],
advancedOrder.parameters.zoneHash,
advancedOrder.parameters.orderType,
orderToExecute.offerer,
advancedOrder.parameters.zone
);
}
}
// Return the array containing available orders.
return availableOrders;
}
/**
* @dev Internal function to convert a spent item to an equivalent
* ReceivedItem with a specified recipient.
*
* @param offerItem The "offerItem" represented by a SpentItem
* struct.
* @param recipient The intended recipient of the converted
* ReceivedItem
*
* @return ReceivedItem The derived ReceivedItem including the
* specified recipient.
*/
function _convertSpentItemToReceivedItemWithRecipient(
SpentItem memory offerItem,
address recipient
) internal pure returns (ReceivedItem memory) {
address payable _recipient;
_recipient = payable(recipient);
return
ReceivedItem(
offerItem.itemType,
offerItem.token,
offerItem.identifier,
offerItem.amount,
_recipient
);
}
/**
* @dev Internal function to match an arbitrary number of full or partial
* orders, each with an arbitrary number of items for offer and
* consideration, supplying criteria resolvers containing specific
* token identifiers and associated proofs as well as fulfillments
* allocating offer components to consideration components.
*
* @param advancedOrders The advanced orders to match. Note that both the
* offerer and fulfiller on each order must first
* approve this contract (or their conduit if
* indicated by the order) to transfer any relevant
* tokens on their behalf and each consideration
* recipient must implement `onERC1155Received` in
* order to receive ERC1155 tokens. Also note that
* the offer and consideration components for each
* order must have no remainder after multiplying
* the respective amount with the supplied fraction
* in order for the group of partial fills to be
* considered valid.
* @param criteriaResolvers An array where each element contains a reference
* to a specific order as well as that order's
* offer or consideration, a token identifier, and
* a proof that the supplied token identifier is
* contained in the order's merkle root. Note that
* an empty root indicates that any (transferable)
* token identifier is valid and that no associated
* proof needs to be supplied.
* @param fulfillments An array of elements allocating offer components
* to consideration components. Note that each
* consideration component must be fully met in
* order for the match operation to be valid.
* @param recipient The intended recipient for all unspent offer
* item amounts.
*
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the
* given orders.
*/
function _matchAdvancedOrders(
AdvancedOrder[] memory advancedOrders,
CriteriaResolver[] memory criteriaResolvers,
Fulfillment[] calldata fulfillments,
address recipient
) internal returns (Execution[] memory executions) {
// Convert Advanced Orders to Orders to Execute
OrderToExecute[] memory ordersToExecute = (
_convertAdvancedToOrdersToExecute(advancedOrders)
);
// Validate orders, apply amounts, & determine if they utilize conduits.
(
bytes32[] memory orderHashes,
bool containsNonOpen
) = _validateOrdersAndPrepareToFulfill(
advancedOrders,
ordersToExecute,
criteriaResolvers,
OrderValidationParams(
true, // Signifies that invalid orders should revert.
advancedOrders.length,
recipient
)
);
// Emit OrdersMatched event.
emit OrdersMatched(orderHashes);
// Fulfill the orders using the supplied fulfillments.
return
_fulfillAdvancedOrders(
advancedOrders,
ordersToExecute,
fulfillments,
orderHashes,
recipient,
containsNonOpen
);
}
/**
* @dev Internal function to fulfill an arbitrary number of orders, either
* full or partial, after validating, adjusting amounts, and applying
* criteria resolvers.
*
* @param ordersToExecute The orders to match, including a fraction to
* attempt to fill for each order.
* @param fulfillments An array of elements allocating offer
* components to consideration components. Note
* that the final amount of each consideration
* component must be zero for a match operation to
* be considered valid.
* @param orderHashes An array of order hashes for each order.
*
* @param containsNonOpen A boolean indicating whether any restricted or
* contract orders are present within the provided
* array of advanced orders.
*
* @return executions An array of elements indicating the sequence
* of transfers performed as part of
* matching the given orders.
*/
function _fulfillAdvancedOrders(
AdvancedOrder[] memory advancedOrders,
OrderToExecute[] memory ordersToExecute,
Fulfillment[] calldata fulfillments,
bytes32[] memory orderHashes,
address recipient,
bool containsNonOpen
) internal returns (Execution[] memory executions) {
// Retrieve fulfillments array length and place on the stack.
uint256 totalFulfillments = fulfillments.length;
// Allocate executions by fulfillment and apply them to each execution.
executions = new Execution[](totalFulfillments);
// Iterate over each fulfillment.
for (uint256 i = 0; i < totalFulfillments; ++i) {
/// Retrieve the fulfillment in question.
Fulfillment calldata fulfillment = fulfillments[i];
// Derive the execution corresponding with the fulfillment and
// assign the execution to the executions array.
executions[i] = _applyFulfillment(
ordersToExecute,
fulfillment.offerComponents,
fulfillment.considerationComponents,
i
);
}
// Perform final checks and execute orders.
_performFinalChecksAndExecuteOrders(
advancedOrders,
ordersToExecute,
executions,
orderHashes,
recipient,
containsNonOpen
);
// Return executions.
return executions;
}
/**
* @dev Internal view function to determine whether a status update failure
* should cause a revert or allow a skipped order. The call must revert
* if an `authorizeOrder` call has been successfully performed and the
* status update cannot be performed, regardless of whether the order
* could be otherwise marked as skipped. Note that a revert is not
* required on a failed update if the call originates from the zone, as
* no `authorizeOrder` call is performed in that case.
*
* @param orderParameters The order parameters in question.
* @param revertOnInvalid A boolean indicating whether the call should
* revert for non-restricted order types.
*
* @return revertOnFailedUpdate A boolean indicating whether the order
* should revert on a failed status update.
*/
function _revertOnFailedUpdate(
OrderParameters memory orderParameters,
bool revertOnInvalid
) internal view returns (bool revertOnFailedUpdate) {
OrderType orderType = orderParameters.orderType;
address zone = orderParameters.zone;
return (revertOnInvalid ||
((orderType == OrderType.FULL_RESTRICTED ||
orderType == OrderType.PARTIAL_RESTRICTED) &&
zone != msg.sender));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
enum OrderType {
// 0: no partial fills, anyone can execute
FULL_OPEN,
// 1: partial fills supported, anyone can execute
PARTIAL_OPEN,
// 2: no partial fills, only offerer or zone can execute
FULL_RESTRICTED,
// 3: partial fills supported, only offerer or zone can execute
PARTIAL_RESTRICTED,
// 4: contract order type
CONTRACT
}
enum BasicOrderType {
// 0: no partial fills, anyone can execute
ETH_TO_ERC721_FULL_OPEN,
// 1: partial fills supported, anyone can execute
ETH_TO_ERC721_PARTIAL_OPEN,
// 2: no partial fills, only offerer or zone can execute
ETH_TO_ERC721_FULL_RESTRICTED,
// 3: partial fills supported, only offerer or zone can execute
ETH_TO_ERC721_PARTIAL_RESTRICTED,
// 4: no partial fills, anyone can execute
ETH_TO_ERC1155_FULL_OPEN,
// 5: partial fills supported, anyone can execute
ETH_TO_ERC1155_PARTIAL_OPEN,
// 6: no partial fills, only offerer or zone can execute
ETH_TO_ERC1155_FULL_RESTRICTED,
// 7: partial fills supported, only offerer or zone can execute
ETH_TO_ERC1155_PARTIAL_RESTRICTED,
// 8: no partial fills, anyone can execute
ERC20_TO_ERC721_FULL_OPEN,
// 9: partial fills supported, anyone can execute
ERC20_TO_ERC721_PARTIAL_OPEN,
// 10: no partial fills, only offerer or zone can execute
ERC20_TO_ERC721_FULL_RESTRICTED,
// 11: partial fills supported, only offerer or zone can execute
ERC20_TO_ERC721_PARTIAL_RESTRICTED,
// 12: no partial fills, anyone can execute
ERC20_TO_ERC1155_FULL_OPEN,
// 13: partial fills supported, anyone can execute
ERC20_TO_ERC1155_PARTIAL_OPEN,
// 14: no partial fills, only offerer or zone can execute
ERC20_TO_ERC1155_FULL_RESTRICTED,
// 15: partial fills supported, only offerer or zone can execute
ERC20_TO_ERC1155_PARTIAL_RESTRICTED,
// 16: no partial fills, anyone can execute
ERC721_TO_ERC20_FULL_OPEN,
// 17: partial fills supported, anyone can execute
ERC721_TO_ERC20_PARTIAL_OPEN,
// 18: no partial fills, only offerer or zone can execute
ERC721_TO_ERC20_FULL_RESTRICTED,
// 19: partial fills supported, only offerer or zone can execute
ERC721_TO_ERC20_PARTIAL_RESTRICTED,
// 20: no partial fills, anyone can execute
ERC1155_TO_ERC20_FULL_OPEN,
// 21: partial fills supported, anyone can execute
ERC1155_TO_ERC20_PARTIAL_OPEN,
// 22: no partial fills, only offerer or zone can execute
ERC1155_TO_ERC20_FULL_RESTRICTED,
// 23: partial fills supported, only offerer or zone can execute
ERC1155_TO_ERC20_PARTIAL_RESTRICTED
}
enum BasicOrderRouteType {
// 0: provide Ether (or other native token) to receive offered ERC721 item.
ETH_TO_ERC721,
// 1: provide Ether (or other native token) to receive offered ERC1155 item.
ETH_TO_ERC1155,
// 2: provide ERC20 item to receive offered ERC721 item.
ERC20_TO_ERC721,
// 3: provide ERC20 item to receive offered ERC1155 item.
ERC20_TO_ERC1155,
// 4: provide ERC721 item to receive offered ERC20 item.
ERC721_TO_ERC20,
// 5: provide ERC1155 item to receive offered ERC20 item.
ERC1155_TO_ERC20
}
enum ItemType {
// 0: ETH on mainnet, MATIC on polygon, etc.
NATIVE,
// 1: ERC20 items (ERC777 and ERC20 analogues could also technically work)
ERC20,
// 2: ERC721 items
ERC721,
// 3: ERC1155 items
ERC1155,
// 4: ERC721 items where a number of tokenIds are supported
ERC721_WITH_CRITERIA,
// 5: ERC1155 items where a number of ids are supported
ERC1155_WITH_CRITERIA
}
enum Side {
// 0: Items that can be spent
OFFER,
// 1: Items that must be received
CONSIDERATION
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
BasicOrderType,
ItemType,
OrderType,
Side
} from "./ConsiderationEnums.sol";
import {
CalldataPointer,
MemoryPointer
} from "../helpers/PointerLibraries.sol";
/**
* @dev An order contains eleven components: an offerer, a zone (or account that
* can cancel the order or restrict who can fulfill the order depending on
* the type), the order type (specifying partial fill support as well as
* restricted order status), the start and end time, a hash that will be
* provided to the zone when validating restricted orders, a salt, a key
* corresponding to a given conduit, a counter, and an arbitrary number of
* offer items that can be spent along with consideration items that must
* be received by their respective recipient.
*/
struct OrderComponents {
address offerer;
address zone;
OfferItem[] offer;
ConsiderationItem[] consideration;
OrderType orderType;
uint256 startTime;
uint256 endTime;
bytes32 zoneHash;
uint256 salt;
bytes32 conduitKey;
uint256 counter;
}
/**
* @dev An offer item has five components: an item type (ETH or other native
* tokens, ERC20, ERC721, and ERC1155, as well as criteria-based ERC721 and
* ERC1155), a token address, a dual-purpose "identifierOrCriteria"
* component that will either represent a tokenId or a merkle root
* depending on the item type, and a start and end amount that support
* increasing or decreasing amounts over the duration of the respective
* order.
*/
struct OfferItem {
ItemType itemType;
address token;
uint256 identifierOrCriteria;
uint256 startAmount;
uint256 endAmount;
}
/**
* @dev A consideration item has the same five components as an offer item and
* an additional sixth component designating the required recipient of the
* item.
*/
struct ConsiderationItem {
ItemType itemType;
address token;
uint256 identifierOrCriteria;
uint256 startAmount;
uint256 endAmount;
address payable recipient;
}
/**
* @dev A spent item is translated from a utilized offer item and has four
* components: an item type (ETH or other native tokens, ERC20, ERC721, and
* ERC1155), a token address, a tokenId, and an amount.
*/
struct SpentItem {
ItemType itemType;
address token;
uint256 identifier;
uint256 amount;
}
/**
* @dev A received item is translated from a utilized consideration item and has
* the same four components as a spent item, as well as an additional fifth
* component designating the required recipient of the item.
*/
struct ReceivedItem {
ItemType itemType;
address token;
uint256 identifier;
uint256 amount;
address payable recipient;
}
/**
* @dev For basic orders involving ETH / native / ERC20 <=> ERC721 / ERC1155
* matching, a group of six functions may be called that only requires a
* subset of the usual order arguments. Note the use of a "basicOrderType"
* enum; this represents both the usual order type as well as the "route"
* of the basic order (a simple derivation function for the basic order
* type is `basicOrderType = orderType + (4 * basicOrderRoute)`.)
*/
struct BasicOrderParameters {
// calldata offset
address considerationToken; // 0x24
uint256 considerationIdentifier; // 0x44
uint256 considerationAmount; // 0x64
address payable offerer; // 0x84
address zone; // 0xa4
address offerToken; // 0xc4
uint256 offerIdentifier; // 0xe4
uint256 offerAmount; // 0x104
BasicOrderType basicOrderType; // 0x124
uint256 startTime; // 0x144
uint256 endTime; // 0x164
bytes32 zoneHash; // 0x184
uint256 salt; // 0x1a4
bytes32 offererConduitKey; // 0x1c4
bytes32 fulfillerConduitKey; // 0x1e4
uint256 totalOriginalAdditionalRecipients; // 0x204
AdditionalRecipient[] additionalRecipients; // 0x224
bytes signature; // 0x244
// Total length, excluding dynamic array data: 0x264 (580)
}
/**
* @dev Basic orders can supply any number of additional recipients, with the
* implied assumption that they are supplied from the offered ETH (or other
* native token) or ERC20 token for the order.
*/
struct AdditionalRecipient {
uint256 amount;
address payable recipient;
}
/**
* @dev The full set of order components, with the exception of the counter,
* must be supplied when fulfilling more sophisticated orders or groups of
* orders. The total number of original consideration items must also be
* supplied, as the caller may specify additional consideration items.
*/
struct OrderParameters {
address offerer; // 0x00
address zone; // 0x20
OfferItem[] offer; // 0x40
ConsiderationItem[] consideration; // 0x60
OrderType orderType; // 0x80
uint256 startTime; // 0xa0
uint256 endTime; // 0xc0
bytes32 zoneHash; // 0xe0
uint256 salt; // 0x100
bytes32 conduitKey; // 0x120
uint256 totalOriginalConsiderationItems; // 0x140
// offer.length // 0x160
}
/**
* @dev Orders require a signature in addition to the other order parameters.
*/
struct Order {
OrderParameters parameters;
bytes signature;
}
/**
* @dev Advanced orders include a numerator (i.e. a fraction to attempt to fill)
* and a denominator (the total size of the order) in addition to the
* signature and other order parameters. It also supports an optional field
* for supplying extra data; this data will be provided to the zone if the
* order type is restricted and the zone is not the caller, or will be
* provided to the offerer as context for contract order types.
*/
struct AdvancedOrder {
OrderParameters parameters;
uint120 numerator;
uint120 denominator;
bytes signature;
bytes extraData;
}
/**
* @dev Orders can be validated (either explicitly via `validate`, or as a
* consequence of a full or partial fill), specifically cancelled (they can
* also be cancelled in bulk via incrementing a per-zone counter), and
* partially or fully filled (with the fraction filled represented by a
* numerator and denominator).
*/
struct OrderStatus {
bool isValidated;
bool isCancelled;
uint120 numerator;
uint120 denominator;
}
/**
* @dev A criteria resolver specifies an order, side (offer vs. consideration),
* and item index. It then provides a chosen identifier (i.e. tokenId)
* alongside a merkle proof demonstrating the identifier meets the required
* criteria.
*/
struct CriteriaResolver {
uint256 orderIndex;
Side side;
uint256 index;
uint256 identifier;
bytes32[] criteriaProof;
}
/**
* @dev A fulfillment is applied to a group of orders. It decrements a series of
* offer and consideration items, then generates a single execution
* element. A given fulfillment can be applied to as many offer and
* consideration items as desired, but must contain at least one offer and
* at least one consideration that match. The fulfillment must also remain
* consistent on all key parameters across all offer items (same offerer,
* token, type, tokenId, and conduit preference) as well as across all
* consideration items (token, type, tokenId, and recipient).
*/
struct Fulfillment {
FulfillmentComponent[] offerComponents;
FulfillmentComponent[] considerationComponents;
}
/**
* @dev Each fulfillment component contains one index referencing a specific
* order and another referencing a specific offer or consideration item.
*/
struct FulfillmentComponent {
uint256 orderIndex;
uint256 itemIndex;
}
/**
* @dev An execution is triggered once all consideration items have been zeroed
* out. It sends the item in question from the offerer to the item's
* recipient, optionally sourcing approvals from either this contract
* directly or from the offerer's chosen conduit if one is specified. An
* execution is not provided as an argument, but rather is derived via
* orders, criteria resolvers, and fulfillments (where the total number of
* executions will be less than or equal to the total number of indicated
* fulfillments) and returned as part of `matchOrders`.
*/
struct Execution {
ReceivedItem item;
address offerer;
bytes32 conduitKey;
}
/**
* @dev Restricted orders are validated post-execution by calling validateOrder
* on the zone. This struct provides context about the order fulfillment
* and any supplied extraData, as well as all order hashes fulfilled in a
* call to a match or fulfillAvailable method.
*/
struct ZoneParameters {
bytes32 orderHash;
address fulfiller;
address offerer;
SpentItem[] offer;
ReceivedItem[] consideration;
bytes extraData;
bytes32[] orderHashes;
uint256 startTime;
uint256 endTime;
bytes32 zoneHash;
}
/**
* @dev Zones and contract offerers can communicate which schemas they implement
* along with any associated metadata related to each schema.
*/
struct Schema {
uint256 id;
bytes metadata;
}
using StructPointers for OrderComponents global;
using StructPointers for OfferItem global;
using StructPointers for ConsiderationItem global;
using StructPointers for SpentItem global;
using StructPointers for ReceivedItem global;
using StructPointers for BasicOrderParameters global;
using StructPointers for AdditionalRecipient global;
using StructPointers for OrderParameters global;
using StructPointers for Order global;
using StructPointers for AdvancedOrder global;
using StructPointers for OrderStatus global;
using StructPointers for CriteriaResolver global;
using StructPointers for Fulfillment global;
using StructPointers for FulfillmentComponent global;
using StructPointers for Execution global;
using StructPointers for ZoneParameters global;
/**
* @dev This library provides a set of functions for converting structs to
* pointers.
*/
library StructPointers {
/**
* @dev Get a MemoryPointer from OrderComponents.
*
* @param obj The OrderComponents object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
OrderComponents memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from OrderComponents.
*
* @param obj The OrderComponents object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
OrderComponents calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from OfferItem.
*
* @param obj The OfferItem object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
OfferItem memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from OfferItem.
*
* @param obj The OfferItem object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
OfferItem calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from ConsiderationItem.
*
* @param obj The ConsiderationItem object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
ConsiderationItem memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from ConsiderationItem.
*
* @param obj The ConsiderationItem object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
ConsiderationItem calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from SpentItem.
*
* @param obj The SpentItem object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
SpentItem memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from SpentItem.
*
* @param obj The SpentItem object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
SpentItem calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from ReceivedItem.
*
* @param obj The ReceivedItem object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
ReceivedItem memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from ReceivedItem.
*
* @param obj The ReceivedItem object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
ReceivedItem calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from BasicOrderParameters.
*
* @param obj The BasicOrderParameters object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
BasicOrderParameters memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from BasicOrderParameters.
*
* @param obj The BasicOrderParameters object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
BasicOrderParameters calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from AdditionalRecipient.
*
* @param obj The AdditionalRecipient object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
AdditionalRecipient memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from AdditionalRecipient.
*
* @param obj The AdditionalRecipient object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
AdditionalRecipient calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from OrderParameters.
*
* @param obj The OrderParameters object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
OrderParameters memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from OrderParameters.
*
* @param obj The OrderParameters object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
OrderParameters calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from Order.
*
* @param obj The Order object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
Order memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from Order.
*
* @param obj The Order object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
Order calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from AdvancedOrder.
*
* @param obj The AdvancedOrder object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
AdvancedOrder memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from AdvancedOrder.
*
* @param obj The AdvancedOrder object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
AdvancedOrder calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from OrderStatus.
*
* @param obj The OrderStatus object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
OrderStatus memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from OrderStatus.
*
* @param obj The OrderStatus object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
OrderStatus calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from CriteriaResolver.
*
* @param obj The CriteriaResolver object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
CriteriaResolver memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from CriteriaResolver.
*
* @param obj The CriteriaResolver object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
CriteriaResolver calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from Fulfillment.
*
* @param obj The Fulfillment object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
Fulfillment memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from Fulfillment.
*
* @param obj The Fulfillment object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
Fulfillment calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from FulfillmentComponent.
*
* @param obj The FulfillmentComponent object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
FulfillmentComponent memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from FulfillmentComponent.
*
* @param obj The FulfillmentComponent object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
FulfillmentComponent calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from Execution.
*
* @param obj The Execution object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
Execution memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from Execution.
*
* @param obj The Execution object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
Execution calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a MemoryPointer from ZoneParameters.
*
* @param obj The ZoneParameters object.
*
* @return ptr The MemoryPointer.
*/
function toMemoryPointer(
ZoneParameters memory obj
) internal pure returns (MemoryPointer ptr) {
assembly {
ptr := obj
}
}
/**
* @dev Get a CalldataPointer from ZoneParameters.
*
* @param obj The ZoneParameters object.
*
* @return ptr The CalldataPointer.
*/
function toCalldataPointer(
ZoneParameters calldata obj
) internal pure returns (CalldataPointer ptr) {
assembly {
ptr := obj
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
AdvancedOrder,
BasicOrderParameters,
CriteriaResolver,
Execution,
Fulfillment,
FulfillmentComponent,
Order,
OrderComponents
} from "../lib/ConsiderationStructs.sol";
/**
* @title ConsiderationInterface
* @author 0age
* @custom:version 1.6
* @notice Consideration is a generalized native token/ERC20/ERC721/ERC1155
* marketplace. It minimizes external calls to the greatest extent
* possible and provides lightweight methods for common routes as well
* as more flexible methods for composing advanced orders.
*
* @dev ConsiderationInterface contains all external function interfaces for
* Consideration.
*/
interface ConsiderationInterface {
/**
* @notice Fulfill an order offering an ERC721 token by supplying Ether (or
* the native token for the given chain) as consideration for the
* order. An arbitrary number of "additional recipients" may also be
* supplied which will each receive native tokens from the fulfiller
* as consideration.
*
* @param parameters Additional information on the fulfilled order. Note
* that the offerer must first approve this contract (or
* their preferred conduit if indicated by the order) for
* their offered ERC721 token to be transferred.
*
* @return fulfilled A boolean indicating whether the order has been
* successfully fulfilled.
*/
function fulfillBasicOrder(
BasicOrderParameters calldata parameters
) external payable returns (bool fulfilled);
/**
* @notice Fulfill an order with an arbitrary number of items for offer and
* consideration. Note that this function does not support
* criteria-based orders or partial filling of orders (though
* filling the remainder of a partially-filled order is supported).
*
* @param order The order to fulfill. Note that both the
* offerer and the fulfiller must first approve
* this contract (or the corresponding conduit if
* indicated) to transfer any relevant tokens on
* their behalf and that contracts must implement
* `onERC1155Received` to receive ERC1155 tokens
* as consideration.
* @param fulfillerConduitKey A bytes32 value indicating what conduit, if
* any, to source the fulfiller's token approvals
* from. The zero hash signifies that no conduit
* should be used, with direct approvals set on
* Consideration.
*
* @return fulfilled A boolean indicating whether the order has been
* successfully fulfilled.
*/
function fulfillOrder(
Order calldata order,
bytes32 fulfillerConduitKey
) external payable returns (bool fulfilled);
/**
* @notice Fill an order, fully or partially, with an arbitrary number of
* items for offer and consideration alongside criteria resolvers
* containing specific token identifiers and associated proofs.
*
* @param advancedOrder The order to fulfill along with the fraction
* of the order to attempt to fill. Note that
* both the offerer and the fulfiller must first
* approve this contract (or their preferred
* conduit if indicated by the order) to transfer
* any relevant tokens on their behalf and that
* contracts must implement `onERC1155Received`
* to receive ERC1155 tokens as consideration.
* Also note that all offer and consideration
* components must have no remainder after
* multiplication of the respective amount with
* the supplied fraction for the partial fill to
* be considered valid.
* @param criteriaResolvers An array where each element contains a
* reference to a specific offer or
* consideration, a token identifier, and a proof
* that the supplied token identifier is
* contained in the merkle root held by the item
* in question's criteria element. Note that an
* empty criteria indicates that any
* (transferable) token identifier on the token
* in question is valid and that no associated
* proof needs to be supplied.
* @param fulfillerConduitKey A bytes32 value indicating what conduit, if
* any, to source the fulfiller's token approvals
* from. The zero hash signifies that no conduit
* should be used, with direct approvals set on
* Consideration.
* @param recipient The intended recipient for all received items,
* with `address(0)` indicating that the caller
* should receive the items.
*
* @return fulfilled A boolean indicating whether the order has been
* successfully fulfilled.
*/
function fulfillAdvancedOrder(
AdvancedOrder calldata advancedOrder,
CriteriaResolver[] calldata criteriaResolvers,
bytes32 fulfillerConduitKey,
address recipient
) external payable returns (bool fulfilled);
/**
* @notice Attempt to fill a group of orders, each with an arbitrary number
* of items for offer and consideration. Any order that is not
* currently active, has already been fully filled, or has been
* cancelled will be omitted. Remaining offer and consideration
* items will then be aggregated where possible as indicated by the
* supplied offer and consideration component arrays and aggregated
* items will be transferred to the fulfiller or to each intended
* recipient, respectively. Note that a failing item transfer or an
* issue with order formatting will cause the entire batch to fail.
* Note that this function does not support criteria-based orders or
* partial filling of orders (though filling the remainder of a
* partially-filled order is supported).
*
* @param orders The orders to fulfill. Note that both
* the offerer and the fulfiller must first
* approve this contract (or the
* corresponding conduit if indicated) to
* transfer any relevant tokens on their
* behalf and that contracts must implement
* `onERC1155Received` to receive ERC1155
* tokens as consideration.
* @param offerFulfillments An array of FulfillmentComponent arrays
* indicating which offer items to attempt
* to aggregate when preparing executions.
* @param considerationFulfillments An array of FulfillmentComponent arrays
* indicating which consideration items to
* attempt to aggregate when preparing
* executions.
* @param fulfillerConduitKey A bytes32 value indicating what conduit,
* if any, to source the fulfiller's token
* approvals from. The zero hash signifies
* that no conduit should be used, with
* direct approvals set on this contract.
* @param maximumFulfilled The maximum number of orders to fulfill.
*
* @return availableOrders An array of booleans indicating if each order
* with an index corresponding to the index of the
* returned boolean was fulfillable or not.
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders. Note that unspent offer item amounts or
* native tokens will not be reflected as part of
* this array.
*/
function fulfillAvailableOrders(
Order[] calldata orders,
FulfillmentComponent[][] calldata offerFulfillments,
FulfillmentComponent[][] calldata considerationFulfillments,
bytes32 fulfillerConduitKey,
uint256 maximumFulfilled
)
external
payable
returns (bool[] memory availableOrders, Execution[] memory executions);
/**
* @notice Attempt to fill a group of orders, fully or partially, with an
* arbitrary number of items for offer and consideration per order
* alongside criteria resolvers containing specific token
* identifiers and associated proofs. Any order that is not
* currently active, has already been fully filled, or has been
* cancelled will be omitted. Remaining offer and consideration
* items will then be aggregated where possible as indicated by the
* supplied offer and consideration component arrays and aggregated
* items will be transferred to the fulfiller or to each intended
* recipient, respectively. Note that a failing item transfer or an
* issue with order formatting will cause the entire batch to fail.
*
* @param advancedOrders The orders to fulfill along with the
* fraction of those orders to attempt to
* fill. Note that both the offerer and the
* fulfiller must first approve this
* contract (or their preferred conduit if
* indicated by the order) to transfer any
* relevant tokens on their behalf and that
* contracts must implement
* `onERC1155Received` to enable receipt of
* ERC1155 tokens as consideration. Also
* note that all offer and consideration
* components must have no remainder after
* multiplication of the respective amount
* with the supplied fraction for an
* order's partial fill amount to be
* considered valid.
* @param criteriaResolvers An array where each element contains a
* reference to a specific offer or
* consideration, a token identifier, and a
* proof that the supplied token identifier
* is contained in the merkle root held by
* the item in question's criteria element.
* Note that an empty criteria indicates
* that any (transferable) token
* identifier on the token in question is
* valid and that no associated proof needs
* to be supplied.
* @param offerFulfillments An array of FulfillmentComponent arrays
* indicating which offer items to attempt
* to aggregate when preparing executions.
* @param considerationFulfillments An array of FulfillmentComponent arrays
* indicating which consideration items to
* attempt to aggregate when preparing
* executions.
* @param fulfillerConduitKey A bytes32 value indicating what conduit,
* if any, to source the fulfiller's token
* approvals from. The zero hash signifies
* that no conduit should be used, with
* direct approvals set on this contract.
* @param recipient The intended recipient for all received
* items, with `address(0)` indicating that
* the caller should receive the items.
* @param maximumFulfilled The maximum number of orders to fulfill.
*
* @return availableOrders An array of booleans indicating if each order
* with an index corresponding to the index of the
* returned boolean was fulfillable or not.
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders. Note that unspent offer item amounts or
* native tokens will not be reflected as part of
* this array.
*/
function fulfillAvailableAdvancedOrders(
AdvancedOrder[] calldata advancedOrders,
CriteriaResolver[] calldata criteriaResolvers,
FulfillmentComponent[][] calldata offerFulfillments,
FulfillmentComponent[][] calldata considerationFulfillments,
bytes32 fulfillerConduitKey,
address recipient,
uint256 maximumFulfilled
)
external
payable
returns (bool[] memory availableOrders, Execution[] memory executions);
/**
* @notice Match an arbitrary number of orders, each with an arbitrary
* number of items for offer and consideration along with a set of
* fulfillments allocating offer components to consideration
* components. Note that this function does not support
* criteria-based or partial filling of orders (though filling the
* remainder of a partially-filled order is supported). Any unspent
* offer item amounts or native tokens will be transferred to the
* caller.
*
* @param orders The orders to match. Note that both the offerer and
* fulfiller on each order must first approve this
* contract (or their conduit if indicated by the order)
* to transfer any relevant tokens on their behalf and
* each consideration recipient must implement
* `onERC1155Received` to enable ERC1155 token receipt.
* @param fulfillments An array of elements allocating offer components to
* consideration components. Note that each
* consideration component must be fully met for the
* match operation to be valid.
*
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders. Note that unspent offer item amounts or
* native tokens will not be reflected as part of this
* array.
*/
function matchOrders(
Order[] calldata orders,
Fulfillment[] calldata fulfillments
) external payable returns (Execution[] memory executions);
/**
* @notice Match an arbitrary number of full or partial orders, each with an
* arbitrary number of items for offer and consideration, supplying
* criteria resolvers containing specific token identifiers and
* associated proofs as well as fulfillments allocating offer
* components to consideration components. Any unspent offer item
* amounts will be transferred to the designated recipient (with the
* null address signifying to use the caller) and any unspent native
* tokens will be returned to the caller.
*
* @param orders The advanced orders to match. Note that both the
* offerer and fulfiller on each order must first
* approve this contract (or a preferred conduit if
* indicated by the order) to transfer any relevant
* tokens on their behalf and each consideration
* recipient must implement `onERC1155Received` in
* order to receive ERC1155 tokens. Also note that
* the offer and consideration components for each
* order must have no remainder after multiplying
* the respective amount with the supplied fraction
* in order for the group of partial fills to be
* considered valid.
* @param criteriaResolvers An array where each element contains a reference
* to a specific order as well as that order's
* offer or consideration, a token identifier, and
* a proof that the supplied token identifier is
* contained in the order's merkle root. Note that
* an empty root indicates that any (transferable)
* token identifier is valid and that no associated
* proof needs to be supplied.
* @param fulfillments An array of elements allocating offer components
* to consideration components. Note that each
* consideration component must be fully met in
* order for the match operation to be valid.
* @param recipient The intended recipient for all unspent offer
* item amounts, or the caller if the null address
* is supplied.
*
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders. Note that unspent offer item amounts or native
* tokens will not be reflected as part of this array.
*/
function matchAdvancedOrders(
AdvancedOrder[] calldata orders,
CriteriaResolver[] calldata criteriaResolvers,
Fulfillment[] calldata fulfillments,
address recipient
) external payable returns (Execution[] memory executions);
/**
* @notice Cancel an arbitrary number of orders. Note that only the offerer
* or the zone of a given order may cancel it. Callers should ensure
* that the intended order was cancelled by calling `getOrderStatus`
* and confirming that `isCancelled` returns `true`.
*
* @param orders The orders to cancel.
*
* @return cancelled A boolean indicating whether the supplied orders have
* been successfully cancelled.
*/
function cancel(
OrderComponents[] calldata orders
) external returns (bool cancelled);
/**
* @notice Validate an arbitrary number of orders, thereby registering their
* signatures as valid and allowing the fulfiller to skip signature
* verification on fulfillment. Note that validated orders may still
* be unfulfillable due to invalid item amounts or other factors;
* callers should determine whether validated orders are fulfillable
* by simulating the fulfillment call prior to execution. Also note
* that anyone can validate a signed order, but only the offerer can
* validate an order without supplying a signature.
*
* @param orders The orders to validate.
*
* @return validated A boolean indicating whether the supplied orders have
* been successfully validated.
*/
function validate(
Order[] calldata orders
) external returns (bool validated);
/**
* @notice Cancel all orders from a given offerer with a given zone in bulk
* by incrementing a counter. Note that only the offerer may
* increment the counter.
*
* @return newCounter The new counter.
*/
function incrementCounter() external returns (uint256 newCounter);
/**
* @notice Fulfill an order offering an ERC721 token by supplying Ether (or
* the native token for the given chain) as consideration for the
* order. An arbitrary number of "additional recipients" may also be
* supplied which will each receive native tokens from the fulfiller
* as consideration. Note that this function costs less gas than
* `fulfillBasicOrder` due to the zero bytes in the function
* selector (0x00000000) which also results in earlier function
* dispatch.
*
* @param parameters Additional information on the fulfilled order. Note
* that the offerer must first approve this contract (or
* their preferred conduit if indicated by the order) for
* their offered ERC721 token to be transferred.
*
* @return fulfilled A boolean indicating whether the order has been
* successfully fulfilled.
*/
function fulfillBasicOrder_efficient_6GL6yc(
BasicOrderParameters calldata parameters
) external payable returns (bool fulfilled);
/**
* @notice Retrieve the order hash for a given order.
*
* @param order The components of the order.
*
* @return orderHash The order hash.
*/
function getOrderHash(
OrderComponents calldata order
) external view returns (bytes32 orderHash);
/**
* @notice Retrieve the status of a given order by hash, including whether
* the order has been cancelled or validated and the fraction of the
* order that has been filled.
*
* @param orderHash The order hash in question.
*
* @return isValidated A boolean indicating whether the order in question
* has been validated (i.e. previously approved or
* partially filled).
* @return isCancelled A boolean indicating whether the order in question
* has been cancelled.
* @return totalFilled The total portion of the order that has been filled
* (i.e. the "numerator").
* @return totalSize The total size of the order that is either filled or
* unfilled (i.e. the "denominator").
*/
function getOrderStatus(
bytes32 orderHash
)
external
view
returns (
bool isValidated,
bool isCancelled,
uint256 totalFilled,
uint256 totalSize
);
/**
* @notice Retrieve the current counter for a given offerer.
*
* @param offerer The offerer in question.
*
* @return counter The current counter.
*/
function getCounter(
address offerer
) external view returns (uint256 counter);
/**
* @notice Retrieve configuration information for this contract.
*
* @return version The contract version.
* @return domainSeparator The domain separator for this contract.
* @return conduitController The conduit Controller set for this contract.
*/
function information()
external
view
returns (
string memory version,
bytes32 domainSeparator,
address conduitController
);
function getContractOffererNonce(
address contractOfferer
) external view returns (uint256 nonce);
/**
* @notice Retrieve the name of this contract.
*
* @return contractName The name of this contract.
*/
function name() external view returns (string memory contractName);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
type CalldataPointer is uint256;
type ReturndataPointer is uint256;
type MemoryPointer is uint256;
using CalldataPointerLib for CalldataPointer global;
using MemoryPointerLib for MemoryPointer global;
using ReturndataPointerLib for ReturndataPointer global;
using CalldataReaders for CalldataPointer global;
using ReturndataReaders for ReturndataPointer global;
using MemoryReaders for MemoryPointer global;
using MemoryWriters for MemoryPointer global;
CalldataPointer constant CalldataStart = CalldataPointer.wrap(0x04);
MemoryPointer constant FreeMemoryPPtr = MemoryPointer.wrap(0x40);
MemoryPointer constant ZeroSlotPtr = MemoryPointer.wrap(0x60);
uint256 constant IdentityPrecompileAddress = 0x4;
uint256 constant OffsetOrLengthMask = 0xffffffff;
uint256 constant _OneWord = 0x20;
uint256 constant _FreeMemoryPointerSlot = 0x40;
/// @dev Allocates `size` bytes in memory by increasing the free memory pointer
/// and returns the memory pointer to the first byte of the allocated region.
// (Free functions cannot have visibility.)
// solhint-disable-next-line func-visibility
function malloc(uint256 size) pure returns (MemoryPointer mPtr) {
assembly {
mPtr := mload(_FreeMemoryPointerSlot)
mstore(_FreeMemoryPointerSlot, add(mPtr, size))
}
}
// (Free functions cannot have visibility.)
// solhint-disable-next-line func-visibility
function getFreeMemoryPointer() pure returns (MemoryPointer mPtr) {
mPtr = FreeMemoryPPtr.readMemoryPointer();
}
// (Free functions cannot have visibility.)
// solhint-disable-next-line func-visibility
function setFreeMemoryPointer(MemoryPointer mPtr) pure {
FreeMemoryPPtr.write(mPtr);
}
library CalldataPointerLib {
function lt(
CalldataPointer a,
CalldataPointer b
) internal pure returns (bool c) {
assembly {
c := lt(a, b)
}
}
function gt(
CalldataPointer a,
CalldataPointer b
) internal pure returns (bool c) {
assembly {
c := gt(a, b)
}
}
function eq(
CalldataPointer a,
CalldataPointer b
) internal pure returns (bool c) {
assembly {
c := eq(a, b)
}
}
function isNull(CalldataPointer a) internal pure returns (bool b) {
assembly {
b := iszero(a)
}
}
/// @dev Resolves an offset stored at `cdPtr + headOffset` to a calldata.
/// pointer `cdPtr` must point to some parent object with a dynamic
/// type's head stored at `cdPtr + headOffset`.
function pptrOffset(
CalldataPointer cdPtr,
uint256 headOffset
) internal pure returns (CalldataPointer cdPtrChild) {
cdPtrChild = cdPtr.offset(
cdPtr.offset(headOffset).readUint256() & OffsetOrLengthMask
);
}
/// @dev Resolves an offset stored at `cdPtr` to a calldata pointer.
/// `cdPtr` must point to some parent object with a dynamic type as its
/// first member, e.g. `struct { bytes data; }`
function pptr(
CalldataPointer cdPtr
) internal pure returns (CalldataPointer cdPtrChild) {
cdPtrChild = cdPtr.offset(cdPtr.readUint256() & OffsetOrLengthMask);
}
/// @dev Returns the calldata pointer one word after `cdPtr`.
function next(
CalldataPointer cdPtr
) internal pure returns (CalldataPointer cdPtrNext) {
assembly {
cdPtrNext := add(cdPtr, _OneWord)
}
}
/// @dev Returns the calldata pointer `_offset` bytes after `cdPtr`.
function offset(
CalldataPointer cdPtr,
uint256 _offset
) internal pure returns (CalldataPointer cdPtrNext) {
assembly {
cdPtrNext := add(cdPtr, _offset)
}
}
/// @dev Copies `size` bytes from calldata starting at `src` to memory at
/// `dst`.
function copy(
CalldataPointer src,
MemoryPointer dst,
uint256 size
) internal pure {
assembly {
calldatacopy(dst, src, size)
}
}
}
library ReturndataPointerLib {
function lt(
ReturndataPointer a,
ReturndataPointer b
) internal pure returns (bool c) {
assembly {
c := lt(a, b)
}
}
function gt(
ReturndataPointer a,
ReturndataPointer b
) internal pure returns (bool c) {
assembly {
c := gt(a, b)
}
}
function eq(
ReturndataPointer a,
ReturndataPointer b
) internal pure returns (bool c) {
assembly {
c := eq(a, b)
}
}
function isNull(ReturndataPointer a) internal pure returns (bool b) {
assembly {
b := iszero(a)
}
}
/// @dev Resolves an offset stored at `rdPtr + headOffset` to a returndata
/// pointer. `rdPtr` must point to some parent object with a dynamic
/// type's head stored at `rdPtr + headOffset`.
function pptrOffset(
ReturndataPointer rdPtr,
uint256 headOffset
) internal pure returns (ReturndataPointer rdPtrChild) {
rdPtrChild = rdPtr.offset(
rdPtr.offset(headOffset).readUint256() & OffsetOrLengthMask
);
}
/// @dev Resolves an offset stored at `rdPtr` to a returndata pointer.
/// `rdPtr` must point to some parent object with a dynamic type as its
/// first member, e.g. `struct { bytes data; }`
function pptr(
ReturndataPointer rdPtr
) internal pure returns (ReturndataPointer rdPtrChild) {
rdPtrChild = rdPtr.offset(rdPtr.readUint256() & OffsetOrLengthMask);
}
/// @dev Returns the returndata pointer one word after `cdPtr`.
function next(
ReturndataPointer rdPtr
) internal pure returns (ReturndataPointer rdPtrNext) {
assembly {
rdPtrNext := add(rdPtr, _OneWord)
}
}
/// @dev Returns the returndata pointer `_offset` bytes after `cdPtr`.
function offset(
ReturndataPointer rdPtr,
uint256 _offset
) internal pure returns (ReturndataPointer rdPtrNext) {
assembly {
rdPtrNext := add(rdPtr, _offset)
}
}
/// @dev Copies `size` bytes from returndata starting at `src` to memory at
/// `dst`.
function copy(
ReturndataPointer src,
MemoryPointer dst,
uint256 size
) internal pure {
assembly {
returndatacopy(dst, src, size)
}
}
}
library MemoryPointerLib {
function copy(
MemoryPointer src,
MemoryPointer dst,
uint256 size
) internal view {
assembly {
let success := staticcall(
gas(),
IdentityPrecompileAddress,
src,
size,
dst,
size
)
if or(iszero(returndatasize()), iszero(success)) {
revert(0, 0)
}
}
}
function lt(
MemoryPointer a,
MemoryPointer b
) internal pure returns (bool c) {
assembly {
c := lt(a, b)
}
}
function gt(
MemoryPointer a,
MemoryPointer b
) internal pure returns (bool c) {
assembly {
c := gt(a, b)
}
}
function eq(
MemoryPointer a,
MemoryPointer b
) internal pure returns (bool c) {
assembly {
c := eq(a, b)
}
}
function isNull(MemoryPointer a) internal pure returns (bool b) {
assembly {
b := iszero(a)
}
}
function hash(
MemoryPointer ptr,
uint256 length
) internal pure returns (bytes32 _hash) {
assembly {
_hash := keccak256(ptr, length)
}
}
/// @dev Returns the memory pointer one word after `mPtr`.
function next(
MemoryPointer mPtr
) internal pure returns (MemoryPointer mPtrNext) {
assembly {
mPtrNext := add(mPtr, _OneWord)
}
}
/// @dev Returns the memory pointer `_offset` bytes after `mPtr`.
function offset(
MemoryPointer mPtr,
uint256 _offset
) internal pure returns (MemoryPointer mPtrNext) {
assembly {
mPtrNext := add(mPtr, _offset)
}
}
/// @dev Resolves a pointer at `mPtr + headOffset` to a memory
/// pointer. `mPtr` must point to some parent object with a dynamic
/// type's pointer stored at `mPtr + headOffset`.
function pptrOffset(
MemoryPointer mPtr,
uint256 headOffset
) internal pure returns (MemoryPointer mPtrChild) {
mPtrChild = mPtr.offset(headOffset).readMemoryPointer();
}
/// @dev Resolves a pointer stored at `mPtr` to a memory pointer.
/// `mPtr` must point to some parent object with a dynamic type as its
/// first member, e.g. `struct { bytes data; }`
function pptr(
MemoryPointer mPtr
) internal pure returns (MemoryPointer mPtrChild) {
mPtrChild = mPtr.readMemoryPointer();
}
}
library CalldataReaders {
/// @dev Reads the value at `cdPtr` and applies a mask to return only the
/// last 4 bytes.
function readMaskedUint256(
CalldataPointer cdPtr
) internal pure returns (uint256 value) {
value = cdPtr.readUint256() & OffsetOrLengthMask;
}
/// @dev Reads the bool at `cdPtr` in calldata.
function readBool(
CalldataPointer cdPtr
) internal pure returns (bool value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the address at `cdPtr` in calldata.
function readAddress(
CalldataPointer cdPtr
) internal pure returns (address value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes1 at `cdPtr` in calldata.
function readBytes1(
CalldataPointer cdPtr
) internal pure returns (bytes1 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes2 at `cdPtr` in calldata.
function readBytes2(
CalldataPointer cdPtr
) internal pure returns (bytes2 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes3 at `cdPtr` in calldata.
function readBytes3(
CalldataPointer cdPtr
) internal pure returns (bytes3 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes4 at `cdPtr` in calldata.
function readBytes4(
CalldataPointer cdPtr
) internal pure returns (bytes4 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes5 at `cdPtr` in calldata.
function readBytes5(
CalldataPointer cdPtr
) internal pure returns (bytes5 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes6 at `cdPtr` in calldata.
function readBytes6(
CalldataPointer cdPtr
) internal pure returns (bytes6 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes7 at `cdPtr` in calldata.
function readBytes7(
CalldataPointer cdPtr
) internal pure returns (bytes7 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes8 at `cdPtr` in calldata.
function readBytes8(
CalldataPointer cdPtr
) internal pure returns (bytes8 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes9 at `cdPtr` in calldata.
function readBytes9(
CalldataPointer cdPtr
) internal pure returns (bytes9 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes10 at `cdPtr` in calldata.
function readBytes10(
CalldataPointer cdPtr
) internal pure returns (bytes10 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes11 at `cdPtr` in calldata.
function readBytes11(
CalldataPointer cdPtr
) internal pure returns (bytes11 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes12 at `cdPtr` in calldata.
function readBytes12(
CalldataPointer cdPtr
) internal pure returns (bytes12 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes13 at `cdPtr` in calldata.
function readBytes13(
CalldataPointer cdPtr
) internal pure returns (bytes13 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes14 at `cdPtr` in calldata.
function readBytes14(
CalldataPointer cdPtr
) internal pure returns (bytes14 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes15 at `cdPtr` in calldata.
function readBytes15(
CalldataPointer cdPtr
) internal pure returns (bytes15 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes16 at `cdPtr` in calldata.
function readBytes16(
CalldataPointer cdPtr
) internal pure returns (bytes16 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes17 at `cdPtr` in calldata.
function readBytes17(
CalldataPointer cdPtr
) internal pure returns (bytes17 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes18 at `cdPtr` in calldata.
function readBytes18(
CalldataPointer cdPtr
) internal pure returns (bytes18 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes19 at `cdPtr` in calldata.
function readBytes19(
CalldataPointer cdPtr
) internal pure returns (bytes19 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes20 at `cdPtr` in calldata.
function readBytes20(
CalldataPointer cdPtr
) internal pure returns (bytes20 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes21 at `cdPtr` in calldata.
function readBytes21(
CalldataPointer cdPtr
) internal pure returns (bytes21 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes22 at `cdPtr` in calldata.
function readBytes22(
CalldataPointer cdPtr
) internal pure returns (bytes22 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes23 at `cdPtr` in calldata.
function readBytes23(
CalldataPointer cdPtr
) internal pure returns (bytes23 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes24 at `cdPtr` in calldata.
function readBytes24(
CalldataPointer cdPtr
) internal pure returns (bytes24 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes25 at `cdPtr` in calldata.
function readBytes25(
CalldataPointer cdPtr
) internal pure returns (bytes25 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes26 at `cdPtr` in calldata.
function readBytes26(
CalldataPointer cdPtr
) internal pure returns (bytes26 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes27 at `cdPtr` in calldata.
function readBytes27(
CalldataPointer cdPtr
) internal pure returns (bytes27 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes28 at `cdPtr` in calldata.
function readBytes28(
CalldataPointer cdPtr
) internal pure returns (bytes28 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes29 at `cdPtr` in calldata.
function readBytes29(
CalldataPointer cdPtr
) internal pure returns (bytes29 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes30 at `cdPtr` in calldata.
function readBytes30(
CalldataPointer cdPtr
) internal pure returns (bytes30 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes31 at `cdPtr` in calldata.
function readBytes31(
CalldataPointer cdPtr
) internal pure returns (bytes31 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the bytes32 at `cdPtr` in calldata.
function readBytes32(
CalldataPointer cdPtr
) internal pure returns (bytes32 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint8 at `cdPtr` in calldata.
function readUint8(
CalldataPointer cdPtr
) internal pure returns (uint8 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint16 at `cdPtr` in calldata.
function readUint16(
CalldataPointer cdPtr
) internal pure returns (uint16 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint24 at `cdPtr` in calldata.
function readUint24(
CalldataPointer cdPtr
) internal pure returns (uint24 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint32 at `cdPtr` in calldata.
function readUint32(
CalldataPointer cdPtr
) internal pure returns (uint32 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint40 at `cdPtr` in calldata.
function readUint40(
CalldataPointer cdPtr
) internal pure returns (uint40 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint48 at `cdPtr` in calldata.
function readUint48(
CalldataPointer cdPtr
) internal pure returns (uint48 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint56 at `cdPtr` in calldata.
function readUint56(
CalldataPointer cdPtr
) internal pure returns (uint56 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint64 at `cdPtr` in calldata.
function readUint64(
CalldataPointer cdPtr
) internal pure returns (uint64 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint72 at `cdPtr` in calldata.
function readUint72(
CalldataPointer cdPtr
) internal pure returns (uint72 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint80 at `cdPtr` in calldata.
function readUint80(
CalldataPointer cdPtr
) internal pure returns (uint80 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint88 at `cdPtr` in calldata.
function readUint88(
CalldataPointer cdPtr
) internal pure returns (uint88 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint96 at `cdPtr` in calldata.
function readUint96(
CalldataPointer cdPtr
) internal pure returns (uint96 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint104 at `cdPtr` in calldata.
function readUint104(
CalldataPointer cdPtr
) internal pure returns (uint104 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint112 at `cdPtr` in calldata.
function readUint112(
CalldataPointer cdPtr
) internal pure returns (uint112 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint120 at `cdPtr` in calldata.
function readUint120(
CalldataPointer cdPtr
) internal pure returns (uint120 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint128 at `cdPtr` in calldata.
function readUint128(
CalldataPointer cdPtr
) internal pure returns (uint128 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint136 at `cdPtr` in calldata.
function readUint136(
CalldataPointer cdPtr
) internal pure returns (uint136 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint144 at `cdPtr` in calldata.
function readUint144(
CalldataPointer cdPtr
) internal pure returns (uint144 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint152 at `cdPtr` in calldata.
function readUint152(
CalldataPointer cdPtr
) internal pure returns (uint152 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint160 at `cdPtr` in calldata.
function readUint160(
CalldataPointer cdPtr
) internal pure returns (uint160 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint168 at `cdPtr` in calldata.
function readUint168(
CalldataPointer cdPtr
) internal pure returns (uint168 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint176 at `cdPtr` in calldata.
function readUint176(
CalldataPointer cdPtr
) internal pure returns (uint176 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint184 at `cdPtr` in calldata.
function readUint184(
CalldataPointer cdPtr
) internal pure returns (uint184 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint192 at `cdPtr` in calldata.
function readUint192(
CalldataPointer cdPtr
) internal pure returns (uint192 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint200 at `cdPtr` in calldata.
function readUint200(
CalldataPointer cdPtr
) internal pure returns (uint200 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint208 at `cdPtr` in calldata.
function readUint208(
CalldataPointer cdPtr
) internal pure returns (uint208 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint216 at `cdPtr` in calldata.
function readUint216(
CalldataPointer cdPtr
) internal pure returns (uint216 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint224 at `cdPtr` in calldata.
function readUint224(
CalldataPointer cdPtr
) internal pure returns (uint224 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint232 at `cdPtr` in calldata.
function readUint232(
CalldataPointer cdPtr
) internal pure returns (uint232 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint240 at `cdPtr` in calldata.
function readUint240(
CalldataPointer cdPtr
) internal pure returns (uint240 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint248 at `cdPtr` in calldata.
function readUint248(
CalldataPointer cdPtr
) internal pure returns (uint248 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the uint256 at `cdPtr` in calldata.
function readUint256(
CalldataPointer cdPtr
) internal pure returns (uint256 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int8 at `cdPtr` in calldata.
function readInt8(
CalldataPointer cdPtr
) internal pure returns (int8 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int16 at `cdPtr` in calldata.
function readInt16(
CalldataPointer cdPtr
) internal pure returns (int16 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int24 at `cdPtr` in calldata.
function readInt24(
CalldataPointer cdPtr
) internal pure returns (int24 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int32 at `cdPtr` in calldata.
function readInt32(
CalldataPointer cdPtr
) internal pure returns (int32 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int40 at `cdPtr` in calldata.
function readInt40(
CalldataPointer cdPtr
) internal pure returns (int40 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int48 at `cdPtr` in calldata.
function readInt48(
CalldataPointer cdPtr
) internal pure returns (int48 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int56 at `cdPtr` in calldata.
function readInt56(
CalldataPointer cdPtr
) internal pure returns (int56 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int64 at `cdPtr` in calldata.
function readInt64(
CalldataPointer cdPtr
) internal pure returns (int64 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int72 at `cdPtr` in calldata.
function readInt72(
CalldataPointer cdPtr
) internal pure returns (int72 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int80 at `cdPtr` in calldata.
function readInt80(
CalldataPointer cdPtr
) internal pure returns (int80 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int88 at `cdPtr` in calldata.
function readInt88(
CalldataPointer cdPtr
) internal pure returns (int88 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int96 at `cdPtr` in calldata.
function readInt96(
CalldataPointer cdPtr
) internal pure returns (int96 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int104 at `cdPtr` in calldata.
function readInt104(
CalldataPointer cdPtr
) internal pure returns (int104 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int112 at `cdPtr` in calldata.
function readInt112(
CalldataPointer cdPtr
) internal pure returns (int112 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int120 at `cdPtr` in calldata.
function readInt120(
CalldataPointer cdPtr
) internal pure returns (int120 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int128 at `cdPtr` in calldata.
function readInt128(
CalldataPointer cdPtr
) internal pure returns (int128 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int136 at `cdPtr` in calldata.
function readInt136(
CalldataPointer cdPtr
) internal pure returns (int136 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int144 at `cdPtr` in calldata.
function readInt144(
CalldataPointer cdPtr
) internal pure returns (int144 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int152 at `cdPtr` in calldata.
function readInt152(
CalldataPointer cdPtr
) internal pure returns (int152 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int160 at `cdPtr` in calldata.
function readInt160(
CalldataPointer cdPtr
) internal pure returns (int160 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int168 at `cdPtr` in calldata.
function readInt168(
CalldataPointer cdPtr
) internal pure returns (int168 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int176 at `cdPtr` in calldata.
function readInt176(
CalldataPointer cdPtr
) internal pure returns (int176 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int184 at `cdPtr` in calldata.
function readInt184(
CalldataPointer cdPtr
) internal pure returns (int184 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int192 at `cdPtr` in calldata.
function readInt192(
CalldataPointer cdPtr
) internal pure returns (int192 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int200 at `cdPtr` in calldata.
function readInt200(
CalldataPointer cdPtr
) internal pure returns (int200 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int208 at `cdPtr` in calldata.
function readInt208(
CalldataPointer cdPtr
) internal pure returns (int208 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int216 at `cdPtr` in calldata.
function readInt216(
CalldataPointer cdPtr
) internal pure returns (int216 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int224 at `cdPtr` in calldata.
function readInt224(
CalldataPointer cdPtr
) internal pure returns (int224 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int232 at `cdPtr` in calldata.
function readInt232(
CalldataPointer cdPtr
) internal pure returns (int232 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int240 at `cdPtr` in calldata.
function readInt240(
CalldataPointer cdPtr
) internal pure returns (int240 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int248 at `cdPtr` in calldata.
function readInt248(
CalldataPointer cdPtr
) internal pure returns (int248 value) {
assembly {
value := calldataload(cdPtr)
}
}
/// @dev Reads the int256 at `cdPtr` in calldata.
function readInt256(
CalldataPointer cdPtr
) internal pure returns (int256 value) {
assembly {
value := calldataload(cdPtr)
}
}
}
library ReturndataReaders {
/// @dev Reads value at `rdPtr` & applies a mask to return only last 4 bytes
function readMaskedUint256(
ReturndataPointer rdPtr
) internal pure returns (uint256 value) {
value = rdPtr.readUint256() & OffsetOrLengthMask;
}
/// @dev Reads the bool at `rdPtr` in returndata.
function readBool(
ReturndataPointer rdPtr
) internal pure returns (bool value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the address at `rdPtr` in returndata.
function readAddress(
ReturndataPointer rdPtr
) internal pure returns (address value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes1 at `rdPtr` in returndata.
function readBytes1(
ReturndataPointer rdPtr
) internal pure returns (bytes1 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes2 at `rdPtr` in returndata.
function readBytes2(
ReturndataPointer rdPtr
) internal pure returns (bytes2 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes3 at `rdPtr` in returndata.
function readBytes3(
ReturndataPointer rdPtr
) internal pure returns (bytes3 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes4 at `rdPtr` in returndata.
function readBytes4(
ReturndataPointer rdPtr
) internal pure returns (bytes4 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes5 at `rdPtr` in returndata.
function readBytes5(
ReturndataPointer rdPtr
) internal pure returns (bytes5 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes6 at `rdPtr` in returndata.
function readBytes6(
ReturndataPointer rdPtr
) internal pure returns (bytes6 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes7 at `rdPtr` in returndata.
function readBytes7(
ReturndataPointer rdPtr
) internal pure returns (bytes7 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes8 at `rdPtr` in returndata.
function readBytes8(
ReturndataPointer rdPtr
) internal pure returns (bytes8 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes9 at `rdPtr` in returndata.
function readBytes9(
ReturndataPointer rdPtr
) internal pure returns (bytes9 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes10 at `rdPtr` in returndata.
function readBytes10(
ReturndataPointer rdPtr
) internal pure returns (bytes10 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes11 at `rdPtr` in returndata.
function readBytes11(
ReturndataPointer rdPtr
) internal pure returns (bytes11 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes12 at `rdPtr` in returndata.
function readBytes12(
ReturndataPointer rdPtr
) internal pure returns (bytes12 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes13 at `rdPtr` in returndata.
function readBytes13(
ReturndataPointer rdPtr
) internal pure returns (bytes13 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes14 at `rdPtr` in returndata.
function readBytes14(
ReturndataPointer rdPtr
) internal pure returns (bytes14 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes15 at `rdPtr` in returndata.
function readBytes15(
ReturndataPointer rdPtr
) internal pure returns (bytes15 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes16 at `rdPtr` in returndata.
function readBytes16(
ReturndataPointer rdPtr
) internal pure returns (bytes16 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes17 at `rdPtr` in returndata.
function readBytes17(
ReturndataPointer rdPtr
) internal pure returns (bytes17 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes18 at `rdPtr` in returndata.
function readBytes18(
ReturndataPointer rdPtr
) internal pure returns (bytes18 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes19 at `rdPtr` in returndata.
function readBytes19(
ReturndataPointer rdPtr
) internal pure returns (bytes19 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes20 at `rdPtr` in returndata.
function readBytes20(
ReturndataPointer rdPtr
) internal pure returns (bytes20 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes21 at `rdPtr` in returndata.
function readBytes21(
ReturndataPointer rdPtr
) internal pure returns (bytes21 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes22 at `rdPtr` in returndata.
function readBytes22(
ReturndataPointer rdPtr
) internal pure returns (bytes22 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes23 at `rdPtr` in returndata.
function readBytes23(
ReturndataPointer rdPtr
) internal pure returns (bytes23 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes24 at `rdPtr` in returndata.
function readBytes24(
ReturndataPointer rdPtr
) internal pure returns (bytes24 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes25 at `rdPtr` in returndata.
function readBytes25(
ReturndataPointer rdPtr
) internal pure returns (bytes25 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes26 at `rdPtr` in returndata.
function readBytes26(
ReturndataPointer rdPtr
) internal pure returns (bytes26 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes27 at `rdPtr` in returndata.
function readBytes27(
ReturndataPointer rdPtr
) internal pure returns (bytes27 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes28 at `rdPtr` in returndata.
function readBytes28(
ReturndataPointer rdPtr
) internal pure returns (bytes28 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes29 at `rdPtr` in returndata.
function readBytes29(
ReturndataPointer rdPtr
) internal pure returns (bytes29 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes30 at `rdPtr` in returndata.
function readBytes30(
ReturndataPointer rdPtr
) internal pure returns (bytes30 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes31 at `rdPtr` in returndata.
function readBytes31(
ReturndataPointer rdPtr
) internal pure returns (bytes31 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the bytes32 at `rdPtr` in returndata.
function readBytes32(
ReturndataPointer rdPtr
) internal pure returns (bytes32 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint8 at `rdPtr` in returndata.
function readUint8(
ReturndataPointer rdPtr
) internal pure returns (uint8 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint16 at `rdPtr` in returndata.
function readUint16(
ReturndataPointer rdPtr
) internal pure returns (uint16 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint24 at `rdPtr` in returndata.
function readUint24(
ReturndataPointer rdPtr
) internal pure returns (uint24 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint32 at `rdPtr` in returndata.
function readUint32(
ReturndataPointer rdPtr
) internal pure returns (uint32 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint40 at `rdPtr` in returndata.
function readUint40(
ReturndataPointer rdPtr
) internal pure returns (uint40 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint48 at `rdPtr` in returndata.
function readUint48(
ReturndataPointer rdPtr
) internal pure returns (uint48 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint56 at `rdPtr` in returndata.
function readUint56(
ReturndataPointer rdPtr
) internal pure returns (uint56 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint64 at `rdPtr` in returndata.
function readUint64(
ReturndataPointer rdPtr
) internal pure returns (uint64 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint72 at `rdPtr` in returndata.
function readUint72(
ReturndataPointer rdPtr
) internal pure returns (uint72 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint80 at `rdPtr` in returndata.
function readUint80(
ReturndataPointer rdPtr
) internal pure returns (uint80 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint88 at `rdPtr` in returndata.
function readUint88(
ReturndataPointer rdPtr
) internal pure returns (uint88 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint96 at `rdPtr` in returndata.
function readUint96(
ReturndataPointer rdPtr
) internal pure returns (uint96 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint104 at `rdPtr` in returndata.
function readUint104(
ReturndataPointer rdPtr
) internal pure returns (uint104 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint112 at `rdPtr` in returndata.
function readUint112(
ReturndataPointer rdPtr
) internal pure returns (uint112 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint120 at `rdPtr` in returndata.
function readUint120(
ReturndataPointer rdPtr
) internal pure returns (uint120 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint128 at `rdPtr` in returndata.
function readUint128(
ReturndataPointer rdPtr
) internal pure returns (uint128 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint136 at `rdPtr` in returndata.
function readUint136(
ReturndataPointer rdPtr
) internal pure returns (uint136 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint144 at `rdPtr` in returndata.
function readUint144(
ReturndataPointer rdPtr
) internal pure returns (uint144 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint152 at `rdPtr` in returndata.
function readUint152(
ReturndataPointer rdPtr
) internal pure returns (uint152 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint160 at `rdPtr` in returndata.
function readUint160(
ReturndataPointer rdPtr
) internal pure returns (uint160 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint168 at `rdPtr` in returndata.
function readUint168(
ReturndataPointer rdPtr
) internal pure returns (uint168 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint176 at `rdPtr` in returndata.
function readUint176(
ReturndataPointer rdPtr
) internal pure returns (uint176 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint184 at `rdPtr` in returndata.
function readUint184(
ReturndataPointer rdPtr
) internal pure returns (uint184 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint192 at `rdPtr` in returndata.
function readUint192(
ReturndataPointer rdPtr
) internal pure returns (uint192 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint200 at `rdPtr` in returndata.
function readUint200(
ReturndataPointer rdPtr
) internal pure returns (uint200 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint208 at `rdPtr` in returndata.
function readUint208(
ReturndataPointer rdPtr
) internal pure returns (uint208 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint216 at `rdPtr` in returndata.
function readUint216(
ReturndataPointer rdPtr
) internal pure returns (uint216 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint224 at `rdPtr` in returndata.
function readUint224(
ReturndataPointer rdPtr
) internal pure returns (uint224 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint232 at `rdPtr` in returndata.
function readUint232(
ReturndataPointer rdPtr
) internal pure returns (uint232 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint240 at `rdPtr` in returndata.
function readUint240(
ReturndataPointer rdPtr
) internal pure returns (uint240 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint248 at `rdPtr` in returndata.
function readUint248(
ReturndataPointer rdPtr
) internal pure returns (uint248 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the uint256 at `rdPtr` in returndata.
function readUint256(
ReturndataPointer rdPtr
) internal pure returns (uint256 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int8 at `rdPtr` in returndata.
function readInt8(
ReturndataPointer rdPtr
) internal pure returns (int8 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int16 at `rdPtr` in returndata.
function readInt16(
ReturndataPointer rdPtr
) internal pure returns (int16 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int24 at `rdPtr` in returndata.
function readInt24(
ReturndataPointer rdPtr
) internal pure returns (int24 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int32 at `rdPtr` in returndata.
function readInt32(
ReturndataPointer rdPtr
) internal pure returns (int32 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int40 at `rdPtr` in returndata.
function readInt40(
ReturndataPointer rdPtr
) internal pure returns (int40 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int48 at `rdPtr` in returndata.
function readInt48(
ReturndataPointer rdPtr
) internal pure returns (int48 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int56 at `rdPtr` in returndata.
function readInt56(
ReturndataPointer rdPtr
) internal pure returns (int56 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int64 at `rdPtr` in returndata.
function readInt64(
ReturndataPointer rdPtr
) internal pure returns (int64 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int72 at `rdPtr` in returndata.
function readInt72(
ReturndataPointer rdPtr
) internal pure returns (int72 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int80 at `rdPtr` in returndata.
function readInt80(
ReturndataPointer rdPtr
) internal pure returns (int80 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int88 at `rdPtr` in returndata.
function readInt88(
ReturndataPointer rdPtr
) internal pure returns (int88 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int96 at `rdPtr` in returndata.
function readInt96(
ReturndataPointer rdPtr
) internal pure returns (int96 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int104 at `rdPtr` in returndata.
function readInt104(
ReturndataPointer rdPtr
) internal pure returns (int104 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int112 at `rdPtr` in returndata.
function readInt112(
ReturndataPointer rdPtr
) internal pure returns (int112 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int120 at `rdPtr` in returndata.
function readInt120(
ReturndataPointer rdPtr
) internal pure returns (int120 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int128 at `rdPtr` in returndata.
function readInt128(
ReturndataPointer rdPtr
) internal pure returns (int128 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int136 at `rdPtr` in returndata.
function readInt136(
ReturndataPointer rdPtr
) internal pure returns (int136 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int144 at `rdPtr` in returndata.
function readInt144(
ReturndataPointer rdPtr
) internal pure returns (int144 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int152 at `rdPtr` in returndata.
function readInt152(
ReturndataPointer rdPtr
) internal pure returns (int152 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int160 at `rdPtr` in returndata.
function readInt160(
ReturndataPointer rdPtr
) internal pure returns (int160 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int168 at `rdPtr` in returndata.
function readInt168(
ReturndataPointer rdPtr
) internal pure returns (int168 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int176 at `rdPtr` in returndata.
function readInt176(
ReturndataPointer rdPtr
) internal pure returns (int176 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int184 at `rdPtr` in returndata.
function readInt184(
ReturndataPointer rdPtr
) internal pure returns (int184 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int192 at `rdPtr` in returndata.
function readInt192(
ReturndataPointer rdPtr
) internal pure returns (int192 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int200 at `rdPtr` in returndata.
function readInt200(
ReturndataPointer rdPtr
) internal pure returns (int200 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int208 at `rdPtr` in returndata.
function readInt208(
ReturndataPointer rdPtr
) internal pure returns (int208 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int216 at `rdPtr` in returndata.
function readInt216(
ReturndataPointer rdPtr
) internal pure returns (int216 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int224 at `rdPtr` in returndata.
function readInt224(
ReturndataPointer rdPtr
) internal pure returns (int224 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int232 at `rdPtr` in returndata.
function readInt232(
ReturndataPointer rdPtr
) internal pure returns (int232 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int240 at `rdPtr` in returndata.
function readInt240(
ReturndataPointer rdPtr
) internal pure returns (int240 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int248 at `rdPtr` in returndata.
function readInt248(
ReturndataPointer rdPtr
) internal pure returns (int248 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
/// @dev Reads the int256 at `rdPtr` in returndata.
function readInt256(
ReturndataPointer rdPtr
) internal pure returns (int256 value) {
assembly {
returndatacopy(0, rdPtr, _OneWord)
value := mload(0)
}
}
}
library MemoryReaders {
/// @dev Reads the memory pointer at `mPtr` in memory.
function readMemoryPointer(
MemoryPointer mPtr
) internal pure returns (MemoryPointer value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads value at `mPtr` & applies a mask to return only last 4 bytes
function readMaskedUint256(
MemoryPointer mPtr
) internal pure returns (uint256 value) {
value = mPtr.readUint256() & OffsetOrLengthMask;
}
/// @dev Reads the bool at `mPtr` in memory.
function readBool(MemoryPointer mPtr) internal pure returns (bool value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the address at `mPtr` in memory.
function readAddress(
MemoryPointer mPtr
) internal pure returns (address value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes1 at `mPtr` in memory.
function readBytes1(
MemoryPointer mPtr
) internal pure returns (bytes1 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes2 at `mPtr` in memory.
function readBytes2(
MemoryPointer mPtr
) internal pure returns (bytes2 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes3 at `mPtr` in memory.
function readBytes3(
MemoryPointer mPtr
) internal pure returns (bytes3 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes4 at `mPtr` in memory.
function readBytes4(
MemoryPointer mPtr
) internal pure returns (bytes4 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes5 at `mPtr` in memory.
function readBytes5(
MemoryPointer mPtr
) internal pure returns (bytes5 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes6 at `mPtr` in memory.
function readBytes6(
MemoryPointer mPtr
) internal pure returns (bytes6 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes7 at `mPtr` in memory.
function readBytes7(
MemoryPointer mPtr
) internal pure returns (bytes7 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes8 at `mPtr` in memory.
function readBytes8(
MemoryPointer mPtr
) internal pure returns (bytes8 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes9 at `mPtr` in memory.
function readBytes9(
MemoryPointer mPtr
) internal pure returns (bytes9 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes10 at `mPtr` in memory.
function readBytes10(
MemoryPointer mPtr
) internal pure returns (bytes10 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes11 at `mPtr` in memory.
function readBytes11(
MemoryPointer mPtr
) internal pure returns (bytes11 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes12 at `mPtr` in memory.
function readBytes12(
MemoryPointer mPtr
) internal pure returns (bytes12 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes13 at `mPtr` in memory.
function readBytes13(
MemoryPointer mPtr
) internal pure returns (bytes13 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes14 at `mPtr` in memory.
function readBytes14(
MemoryPointer mPtr
) internal pure returns (bytes14 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes15 at `mPtr` in memory.
function readBytes15(
MemoryPointer mPtr
) internal pure returns (bytes15 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes16 at `mPtr` in memory.
function readBytes16(
MemoryPointer mPtr
) internal pure returns (bytes16 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes17 at `mPtr` in memory.
function readBytes17(
MemoryPointer mPtr
) internal pure returns (bytes17 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes18 at `mPtr` in memory.
function readBytes18(
MemoryPointer mPtr
) internal pure returns (bytes18 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes19 at `mPtr` in memory.
function readBytes19(
MemoryPointer mPtr
) internal pure returns (bytes19 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes20 at `mPtr` in memory.
function readBytes20(
MemoryPointer mPtr
) internal pure returns (bytes20 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes21 at `mPtr` in memory.
function readBytes21(
MemoryPointer mPtr
) internal pure returns (bytes21 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes22 at `mPtr` in memory.
function readBytes22(
MemoryPointer mPtr
) internal pure returns (bytes22 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes23 at `mPtr` in memory.
function readBytes23(
MemoryPointer mPtr
) internal pure returns (bytes23 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes24 at `mPtr` in memory.
function readBytes24(
MemoryPointer mPtr
) internal pure returns (bytes24 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes25 at `mPtr` in memory.
function readBytes25(
MemoryPointer mPtr
) internal pure returns (bytes25 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes26 at `mPtr` in memory.
function readBytes26(
MemoryPointer mPtr
) internal pure returns (bytes26 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes27 at `mPtr` in memory.
function readBytes27(
MemoryPointer mPtr
) internal pure returns (bytes27 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes28 at `mPtr` in memory.
function readBytes28(
MemoryPointer mPtr
) internal pure returns (bytes28 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes29 at `mPtr` in memory.
function readBytes29(
MemoryPointer mPtr
) internal pure returns (bytes29 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes30 at `mPtr` in memory.
function readBytes30(
MemoryPointer mPtr
) internal pure returns (bytes30 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes31 at `mPtr` in memory.
function readBytes31(
MemoryPointer mPtr
) internal pure returns (bytes31 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the bytes32 at `mPtr` in memory.
function readBytes32(
MemoryPointer mPtr
) internal pure returns (bytes32 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint8 at `mPtr` in memory.
function readUint8(MemoryPointer mPtr) internal pure returns (uint8 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint16 at `mPtr` in memory.
function readUint16(
MemoryPointer mPtr
) internal pure returns (uint16 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint24 at `mPtr` in memory.
function readUint24(
MemoryPointer mPtr
) internal pure returns (uint24 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint32 at `mPtr` in memory.
function readUint32(
MemoryPointer mPtr
) internal pure returns (uint32 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint40 at `mPtr` in memory.
function readUint40(
MemoryPointer mPtr
) internal pure returns (uint40 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint48 at `mPtr` in memory.
function readUint48(
MemoryPointer mPtr
) internal pure returns (uint48 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint56 at `mPtr` in memory.
function readUint56(
MemoryPointer mPtr
) internal pure returns (uint56 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint64 at `mPtr` in memory.
function readUint64(
MemoryPointer mPtr
) internal pure returns (uint64 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint72 at `mPtr` in memory.
function readUint72(
MemoryPointer mPtr
) internal pure returns (uint72 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint80 at `mPtr` in memory.
function readUint80(
MemoryPointer mPtr
) internal pure returns (uint80 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint88 at `mPtr` in memory.
function readUint88(
MemoryPointer mPtr
) internal pure returns (uint88 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint96 at `mPtr` in memory.
function readUint96(
MemoryPointer mPtr
) internal pure returns (uint96 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint104 at `mPtr` in memory.
function readUint104(
MemoryPointer mPtr
) internal pure returns (uint104 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint112 at `mPtr` in memory.
function readUint112(
MemoryPointer mPtr
) internal pure returns (uint112 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint120 at `mPtr` in memory.
function readUint120(
MemoryPointer mPtr
) internal pure returns (uint120 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint128 at `mPtr` in memory.
function readUint128(
MemoryPointer mPtr
) internal pure returns (uint128 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint136 at `mPtr` in memory.
function readUint136(
MemoryPointer mPtr
) internal pure returns (uint136 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint144 at `mPtr` in memory.
function readUint144(
MemoryPointer mPtr
) internal pure returns (uint144 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint152 at `mPtr` in memory.
function readUint152(
MemoryPointer mPtr
) internal pure returns (uint152 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint160 at `mPtr` in memory.
function readUint160(
MemoryPointer mPtr
) internal pure returns (uint160 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint168 at `mPtr` in memory.
function readUint168(
MemoryPointer mPtr
) internal pure returns (uint168 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint176 at `mPtr` in memory.
function readUint176(
MemoryPointer mPtr
) internal pure returns (uint176 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint184 at `mPtr` in memory.
function readUint184(
MemoryPointer mPtr
) internal pure returns (uint184 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint192 at `mPtr` in memory.
function readUint192(
MemoryPointer mPtr
) internal pure returns (uint192 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint200 at `mPtr` in memory.
function readUint200(
MemoryPointer mPtr
) internal pure returns (uint200 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint208 at `mPtr` in memory.
function readUint208(
MemoryPointer mPtr
) internal pure returns (uint208 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint216 at `mPtr` in memory.
function readUint216(
MemoryPointer mPtr
) internal pure returns (uint216 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint224 at `mPtr` in memory.
function readUint224(
MemoryPointer mPtr
) internal pure returns (uint224 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint232 at `mPtr` in memory.
function readUint232(
MemoryPointer mPtr
) internal pure returns (uint232 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint240 at `mPtr` in memory.
function readUint240(
MemoryPointer mPtr
) internal pure returns (uint240 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint248 at `mPtr` in memory.
function readUint248(
MemoryPointer mPtr
) internal pure returns (uint248 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the uint256 at `mPtr` in memory.
function readUint256(
MemoryPointer mPtr
) internal pure returns (uint256 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int8 at `mPtr` in memory.
function readInt8(MemoryPointer mPtr) internal pure returns (int8 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int16 at `mPtr` in memory.
function readInt16(MemoryPointer mPtr) internal pure returns (int16 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int24 at `mPtr` in memory.
function readInt24(MemoryPointer mPtr) internal pure returns (int24 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int32 at `mPtr` in memory.
function readInt32(MemoryPointer mPtr) internal pure returns (int32 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int40 at `mPtr` in memory.
function readInt40(MemoryPointer mPtr) internal pure returns (int40 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int48 at `mPtr` in memory.
function readInt48(MemoryPointer mPtr) internal pure returns (int48 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int56 at `mPtr` in memory.
function readInt56(MemoryPointer mPtr) internal pure returns (int56 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int64 at `mPtr` in memory.
function readInt64(MemoryPointer mPtr) internal pure returns (int64 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int72 at `mPtr` in memory.
function readInt72(MemoryPointer mPtr) internal pure returns (int72 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int80 at `mPtr` in memory.
function readInt80(MemoryPointer mPtr) internal pure returns (int80 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int88 at `mPtr` in memory.
function readInt88(MemoryPointer mPtr) internal pure returns (int88 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int96 at `mPtr` in memory.
function readInt96(MemoryPointer mPtr) internal pure returns (int96 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int104 at `mPtr` in memory.
function readInt104(
MemoryPointer mPtr
) internal pure returns (int104 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int112 at `mPtr` in memory.
function readInt112(
MemoryPointer mPtr
) internal pure returns (int112 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int120 at `mPtr` in memory.
function readInt120(
MemoryPointer mPtr
) internal pure returns (int120 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int128 at `mPtr` in memory.
function readInt128(
MemoryPointer mPtr
) internal pure returns (int128 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int136 at `mPtr` in memory.
function readInt136(
MemoryPointer mPtr
) internal pure returns (int136 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int144 at `mPtr` in memory.
function readInt144(
MemoryPointer mPtr
) internal pure returns (int144 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int152 at `mPtr` in memory.
function readInt152(
MemoryPointer mPtr
) internal pure returns (int152 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int160 at `mPtr` in memory.
function readInt160(
MemoryPointer mPtr
) internal pure returns (int160 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int168 at `mPtr` in memory.
function readInt168(
MemoryPointer mPtr
) internal pure returns (int168 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int176 at `mPtr` in memory.
function readInt176(
MemoryPointer mPtr
) internal pure returns (int176 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int184 at `mPtr` in memory.
function readInt184(
MemoryPointer mPtr
) internal pure returns (int184 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int192 at `mPtr` in memory.
function readInt192(
MemoryPointer mPtr
) internal pure returns (int192 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int200 at `mPtr` in memory.
function readInt200(
MemoryPointer mPtr
) internal pure returns (int200 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int208 at `mPtr` in memory.
function readInt208(
MemoryPointer mPtr
) internal pure returns (int208 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int216 at `mPtr` in memory.
function readInt216(
MemoryPointer mPtr
) internal pure returns (int216 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int224 at `mPtr` in memory.
function readInt224(
MemoryPointer mPtr
) internal pure returns (int224 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int232 at `mPtr` in memory.
function readInt232(
MemoryPointer mPtr
) internal pure returns (int232 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int240 at `mPtr` in memory.
function readInt240(
MemoryPointer mPtr
) internal pure returns (int240 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int248 at `mPtr` in memory.
function readInt248(
MemoryPointer mPtr
) internal pure returns (int248 value) {
assembly {
value := mload(mPtr)
}
}
/// @dev Reads the int256 at `mPtr` in memory.
function readInt256(
MemoryPointer mPtr
) internal pure returns (int256 value) {
assembly {
value := mload(mPtr)
}
}
}
library MemoryWriters {
/// @dev Writes `valuePtr` to memory at `mPtr`.
function write(MemoryPointer mPtr, MemoryPointer valuePtr) internal pure {
assembly {
mstore(mPtr, valuePtr)
}
}
/// @dev Writes a boolean `value` to `mPtr` in memory.
function write(MemoryPointer mPtr, bool value) internal pure {
assembly {
mstore(mPtr, value)
}
}
/// @dev Writes an address `value` to `mPtr` in memory.
function write(MemoryPointer mPtr, address value) internal pure {
assembly {
mstore(mPtr, value)
}
}
/// @dev Writes a bytes32 `value` to `mPtr` in memory.
/// Separate name to disambiguate literal write parameters.
function writeBytes32(MemoryPointer mPtr, bytes32 value) internal pure {
assembly {
mstore(mPtr, value)
}
}
/// @dev Writes a uint256 `value` to `mPtr` in memory.
function write(MemoryPointer mPtr, uint256 value) internal pure {
assembly {
mstore(mPtr, value)
}
}
/// @dev Writes an int256 `value` to `mPtr` in memory.
/// Separate name to disambiguate literal write parameters.
function writeInt(MemoryPointer mPtr, int256 value) internal pure {
assembly {
mstore(mPtr, value)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import { ItemType, Side } from "seaport-types/src/lib/ConsiderationEnums.sol";
import {
Execution,
FulfillmentComponent,
ReceivedItem,
SpentItem
} from "seaport-types/src/lib/ConsiderationStructs.sol";
import {
ConsiderationItemIndicesAndValidity,
OrderToExecute
} from "./ReferenceConsiderationStructs.sol";
import {
FulfillmentApplicationErrors
} from "seaport-types/src/interfaces/FulfillmentApplicationErrors.sol";
import {
TokenTransferrerErrors
} from "seaport-types/src/interfaces/TokenTransferrerErrors.sol";
/**
* @title FulfillmentApplier
* @author 0age
* @notice FulfillmentApplier contains logic related to applying fulfillments,
* both as part of order matching (where offer items are matched to
* consideration items) as well as fulfilling available orders (where
* order items and consideration items are independently aggregated).
*/
contract ReferenceFulfillmentApplier is
FulfillmentApplicationErrors,
TokenTransferrerErrors
{
/**
* @dev Internal pure function to match offer items to consideration items
* on a group of orders via a supplied fulfillment.
*
* @param ordersToExecute The orders to match.
* @param offerComponents An array designating offer components to
* match to consideration components.
* @param considerationComponents An array designating consideration
* components to match to offer components.
* Note that each consideration amount must
* be zero in order for the match operation
* to be valid.
* @param fulfillmentIndex The index of the fulfillment component
* that does not match the initial offer
* item.
*
* @return execution The transfer performed as a result of the fulfillment.
*/
function _applyFulfillment(
OrderToExecute[] memory ordersToExecute,
FulfillmentComponent[] memory offerComponents,
FulfillmentComponent[] memory considerationComponents,
uint256 fulfillmentIndex
) internal pure returns (Execution memory execution) {
// Ensure 1+ of both offer and consideration components are supplied.
if (
offerComponents.length == 0 || considerationComponents.length == 0
) {
revert OfferAndConsiderationRequiredOnFulfillment();
}
// Recipient does not need to be specified because it will always be set
// to that of the consideration.
// Validate and aggregate consideration items and store the result as a
// ReceivedItem.
ReceivedItem memory considerationItem = (
_aggregateValidFulfillmentConsiderationItems(
ordersToExecute,
considerationComponents
)
);
// Skip aggregating offer items if no consideration items are available.
if (considerationItem.amount == 0) {
return execution;
}
// Validate & aggregate offer items and store result as an Execution.
(
execution
/**
* ItemType itemType,
* address token,
* uint256 identifier,
* address offerer,
* bytes32 conduitKey,
* uint256 offerAmount
*/
) = _aggregateValidFulfillmentOfferItems(
ordersToExecute,
offerComponents,
address(0) // unused
);
// Ensure offer and consideration share types, tokens and identifiers.
if (
execution.item.itemType != considerationItem.itemType ||
execution.item.token != considerationItem.token ||
execution.item.identifier != considerationItem.identifier
) {
revert MismatchedFulfillmentOfferAndConsiderationComponents(
fulfillmentIndex
);
}
// If total consideration amount exceeds the offer amount...
if (considerationItem.amount > execution.item.amount) {
// Retrieve the first consideration component from the fulfillment.
FulfillmentComponent memory targetComponent = (
considerationComponents[0]
);
// Add excess consideration item amount to original array of orders.
ordersToExecute[targetComponent.orderIndex]
.receivedItems[targetComponent.itemIndex]
.amount = considerationItem.amount - execution.item.amount;
// Reduce total consideration amount to equal the offer amount.
considerationItem.amount = execution.item.amount;
} else {
// Retrieve the first offer component from the fulfillment.
FulfillmentComponent memory targetComponent = (offerComponents[0]);
// Add excess offer item amount to the original array of orders.
ordersToExecute[targetComponent.orderIndex]
.spentItems[targetComponent.itemIndex]
.amount = execution.item.amount - considerationItem.amount;
}
// Reuse execution struct with consideration amount and recipient.
// Only set the recipient if the item amount is non-zero.
execution.item.amount = considerationItem.amount;
if (execution.item.amount != 0) {
execution.item.recipient = considerationItem.recipient;
}
// Return the final execution that will be triggered for relevant items.
return execution; // Execution(execution, offerer, conduitKey);
}
/**
* @dev Internal view function to aggregate offer or consideration items
* from a group of orders into a single execution via a supplied array
* of fulfillment components. Items that are not available to aggregate
* will not be included in the aggregated execution.
*
* @param ordersToExecute The orders to aggregate.
* @param side The side (i.e. offer or consideration).
* @param fulfillmentComponents An array designating item components to
* aggregate if part of an available order.
* @param fulfillerConduitKey A bytes32 value indicating what conduit, if
* any, to source the fulfiller's token
* approvals from. The zero hash signifies that
* no conduit should be used (and direct
* approvals set on Consideration)
* @param recipient The intended recipient for all received
* items.
*
* @return _execution The transfer performed as a result of the fulfillment.
*/
function _aggregateAvailable(
OrderToExecute[] memory ordersToExecute,
Side side,
FulfillmentComponent[] memory fulfillmentComponents,
bytes32 fulfillerConduitKey,
address recipient
) internal view returns (Execution memory _execution) {
// Retrieve fulfillment components array length and place on stack.
uint256 totalFulfillmentComponents = fulfillmentComponents.length;
// Ensure at least one fulfillment component has been supplied.
if (totalFulfillmentComponents == 0) {
revert MissingFulfillmentComponentOnAggregation(side);
}
Execution memory execution;
// If the fulfillment components are offer components...
if (side == Side.OFFER) {
// Return execution for aggregated items provided by offerer.
execution = _aggregateValidFulfillmentOfferItems(
ordersToExecute,
fulfillmentComponents,
recipient
);
} else {
// Otherwise, fulfillment components are consideration
// components. Return execution for aggregated items provided by
// the fulfiller.
execution = _aggregateConsiderationItems(
ordersToExecute,
fulfillmentComponents,
fulfillerConduitKey
);
}
return execution;
}
/**
* @dev Internal pure function to check the indicated offer item
* matches original item.
*
* @param orderToExecute The order to compare.
* @param offer The offer to compare.
* @param execution The aggregated offer item.
*
* @return invalidFulfillment A boolean indicating whether the
* fulfillment is invalid.
*/
function _checkMatchingOffer(
OrderToExecute memory orderToExecute,
SpentItem memory offer,
Execution memory execution
) internal pure returns (bool invalidFulfillment) {
return
execution.item.identifier != offer.identifier ||
execution.offerer != orderToExecute.offerer ||
execution.conduitKey != orderToExecute.conduitKey ||
execution.item.itemType != offer.itemType ||
execution.item.token != offer.token;
}
/**
* @dev Internal pure function to aggregate a group of offer items using
* supplied directives on which component items are candidates for
* aggregation, skipping items on orders that are not available.
*
* @param ordersToExecute The orders to aggregate offer items from.
* @param offerComponents An array of FulfillmentComponent structs
* indicating the order index and item index of each
* candidate offer item for aggregation.
* @param recipient The recipient for the aggregated offer items.
*
* @return execution The aggregated offer items.
*/
function _aggregateValidFulfillmentOfferItems(
OrderToExecute[] memory ordersToExecute,
FulfillmentComponent[] memory offerComponents,
address recipient
) internal pure returns (Execution memory execution) {
bool foundItem = false;
// Get the order index and item index of the offer component.
uint256 orderIndex;
uint256 itemIndex;
OrderToExecute memory orderToExecute;
// Declare variables indicating whether the aggregation is invalid.
// Ensure that the order index is not out of range.
bool invalidFulfillment;
// Ensure that no available items have missing amounts.
bool missingItemAmount;
// Loop through the offer components, checking for validity.
for (uint256 i = 0; i < offerComponents.length; ++i) {
// Get the order index and item index of the offer component.
orderIndex = offerComponents[i].orderIndex;
itemIndex = offerComponents[i].itemIndex;
// Ensure that the order index is not out of range.
invalidFulfillment = orderIndex >= ordersToExecute.length;
// Break if invalid.
if (invalidFulfillment) {
break;
}
// Get the order based on offer components order index.
orderToExecute = ordersToExecute[orderIndex];
if (
orderToExecute.numerator != 0 &&
itemIndex < orderToExecute.spentItems.length
) {
// Get the spent item based on the offer components item index.
SpentItem memory offer = orderToExecute.spentItems[itemIndex];
if (!foundItem) {
foundItem = true;
// Create the Execution.
execution = Execution(
ReceivedItem(
offer.itemType,
offer.token,
offer.identifier,
offer.amount,
payable(recipient)
),
orderToExecute.offerer,
orderToExecute.conduitKey
);
// If component index > 0, swap component pointer with
// pointer to first component so that any remainder after
// fulfillment can be added back to the first item.
if (i != 0) {
FulfillmentComponent
memory firstComponent = offerComponents[0];
offerComponents[0] = offerComponents[i];
offerComponents[i] = firstComponent;
}
} else {
// Update the Received Item amount.
execution.item.amount =
execution.item.amount +
offer.amount;
// Ensure indicated offer item matches original item.
invalidFulfillment = _checkMatchingOffer(
orderToExecute,
offer,
execution
);
}
// Ensure the item has a nonzero amount.
missingItemAmount = offer.amount == 0;
invalidFulfillment = invalidFulfillment || missingItemAmount;
// Zero out amount on original offerItem to indicate it's spent.
offer.amount = 0;
// Break if invalid.
if (invalidFulfillment) {
break;
}
}
}
// Revert if an order/item was out of range or was not aggregatable.
if (invalidFulfillment) {
if (missingItemAmount) {
revert MissingItemAmount();
}
revert InvalidFulfillmentComponentData();
}
}
/**
* @dev Internal view function to aggregate consideration items from a group
* of orders into a single execution via a supplied components array.
* Consideration items that are not available to aggregate will not be
* included in the aggregated execution.
*
* @param ordersToExecute The orders to aggregate.
* @param considerationComponents An array designating consideration
* components to aggregate if part of an
* available order.
* @param fulfillerConduitKey A bytes32 value indicating what conduit,
* if any, to source the fulfiller's token
* approvals from. The zero hash signifies
* that no conduit should be used (and direct
* approvals set on Consideration)
*
* @return execution The transfer performed as a result of the fulfillment.
*/
function _aggregateConsiderationItems(
OrderToExecute[] memory ordersToExecute,
FulfillmentComponent[] memory considerationComponents,
bytes32 fulfillerConduitKey
) internal view returns (Execution memory execution) {
// Validate and aggregate consideration items on available orders and
// store result as a ReceivedItem.
ReceivedItem memory receiveConsiderationItem = (
_aggregateValidFulfillmentConsiderationItems(
ordersToExecute,
considerationComponents
)
);
if (receiveConsiderationItem.amount != 0) {
// Return execution for aggregated items provided by the fulfiller.
execution = Execution(
receiveConsiderationItem,
msg.sender,
fulfillerConduitKey
);
} else {
// Return an empty execution if the received item amount is zero.
execution = Execution(
receiveConsiderationItem,
address(0),
bytes32(0)
);
}
}
/**
* @dev Internal pure function to check the indicated consideration item
* matches original item.
*
* @param consideration The consideration to compare.
* @param receivedItem The aggregated received item.
*
* @return invalidFulfillment A boolean indicating whether the fulfillment
* is invalid.
*/
function _checkMatchingConsideration(
ReceivedItem memory consideration,
ReceivedItem memory receivedItem
) internal pure returns (bool invalidFulfillment) {
return
receivedItem.recipient != consideration.recipient ||
receivedItem.itemType != consideration.itemType ||
receivedItem.token != consideration.token ||
receivedItem.identifier != consideration.identifier;
}
/**
* @dev Internal pure function to aggregate a group of consideration items
* using supplied directives on which component items are candidates
* for aggregation, skipping items on orders that are not available.
*
* @param ordersToExecute The orders to aggregate consideration
* items from.
* @param considerationComponents An array of FulfillmentComponent structs
* indicating the order index and item index
* of each candidate consideration item for
* aggregation.
*
* @return receivedItem The aggregated consideration items.
*/
function _aggregateValidFulfillmentConsiderationItems(
OrderToExecute[] memory ordersToExecute,
FulfillmentComponent[] memory considerationComponents
) internal pure returns (ReceivedItem memory receivedItem) {
bool foundItem = false;
// Declare struct in memory to avoid declaring multiple local variables.
ConsiderationItemIndicesAndValidity memory potentialCandidate;
ReceivedItem memory consideration;
OrderToExecute memory orderToExecute;
// Loop through the consideration components and validate
// their fulfillment.
for (uint256 i = 0; i < considerationComponents.length; ++i) {
// Get the order index and item index of the consideration
// component.
potentialCandidate.orderIndex = considerationComponents[i]
.orderIndex;
potentialCandidate.itemIndex = considerationComponents[i].itemIndex;
/// Ensure that the order index is not out of range.
potentialCandidate.invalidFulfillment =
potentialCandidate.orderIndex >= ordersToExecute.length;
// Break if invalid.
if (potentialCandidate.invalidFulfillment) {
break;
}
// Get order based on consideration components order index.
orderToExecute = ordersToExecute[potentialCandidate.orderIndex];
// Confirm that the order is being fulfilled.
if (
orderToExecute.numerator != 0 &&
potentialCandidate.itemIndex <
orderToExecute.receivedItems.length
) {
// Retrieve relevant item using item index.
consideration = orderToExecute.receivedItems[
potentialCandidate.itemIndex
];
if (!foundItem) {
foundItem = true;
// Create the received item.
receivedItem = ReceivedItem(
consideration.itemType,
consideration.token,
consideration.identifier,
consideration.amount,
consideration.recipient
);
// If component index > 0, swap component pointer with
// pointer to first component so that any remainder after
// fulfillment can be added back to the first item.
if (i != 0) {
FulfillmentComponent
memory firstComponent = considerationComponents[0];
considerationComponents[0] = considerationComponents[i];
considerationComponents[i] = firstComponent;
}
} else {
// Update Received Item amount.
receivedItem.amount =
receivedItem.amount +
consideration.amount;
// Ensure the indicated consideration item matches
// original item.
potentialCandidate
.invalidFulfillment = _checkMatchingConsideration(
consideration,
receivedItem
);
}
// Ensure the item has a nonzero amount.
potentialCandidate.missingItemAmount =
consideration.amount == 0;
potentialCandidate.invalidFulfillment =
potentialCandidate.invalidFulfillment ||
potentialCandidate.missingItemAmount;
// Zero out amount on original consideration item to
// indicate it is spent.
consideration.amount = 0;
// Break if invalid.
if (potentialCandidate.invalidFulfillment) {
break;
}
}
}
// Revert if an order/item was out of range or was not aggregatable.
if (potentialCandidate.invalidFulfillment) {
if (potentialCandidate.missingItemAmount) {
revert MissingItemAmount();
}
revert InvalidFulfillmentComponentData();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ItemType,
OrderType
} from "seaport-types/src/lib/ConsiderationEnums.sol";
import {
AdvancedOrder,
ConsiderationItem,
CriteriaResolver,
OfferItem,
Order,
OrderParameters,
ReceivedItem,
SpentItem
} from "seaport-types/src/lib/ConsiderationStructs.sol";
import {
AccumulatorStruct,
FractionData,
OrderToExecute,
OrderValidation
} from "./ReferenceConsiderationStructs.sol";
import {
ReferenceBasicOrderFulfiller
} from "./ReferenceBasicOrderFulfiller.sol";
import { ReferenceCriteriaResolution } from "./ReferenceCriteriaResolution.sol";
import { ReferenceAmountDeriver } from "./ReferenceAmountDeriver.sol";
/**
* @title OrderFulfiller
* @author 0age
* @notice OrderFulfiller contains logic related to order fulfillment.
*/
contract ReferenceOrderFulfiller is
ReferenceBasicOrderFulfiller,
ReferenceCriteriaResolution,
ReferenceAmountDeriver
{
/**
* @dev Derive and set hashes, reference chainId, and associated domain
* separator during deployment.
*
* @param conduitController A contract that deploys conduits, or proxies
* that may optionally be used to transfer approved
* ERC20/721/1155 tokens.
*/
constructor(
address conduitController
) ReferenceBasicOrderFulfiller(conduitController) {}
/**
* @dev Internal function to validate an order and update its status, adjust
* prices based on current time, apply criteria resolvers, determine
* what portion to fill, and transfer relevant tokens.
*
* @param advancedOrder The order to fulfill as well as the fraction
* to fill. Note that all offer and consideration
* components must divide with no remainder for
* the partial fill to be valid.
* @param criteriaResolvers An array where each element contains a
* reference to a specific offer or
* consideration, a token identifier, and a proof
* that the supplied token identifier is
* contained in the order's merkle root. Note
* that a criteria of zero indicates that any
* (transferable) token identifier is valid and
* that no proof needs to be supplied.
* @param fulfillerConduitKey A bytes32 value indicating what conduit, if
* any, to source the fulfiller's token approvals
* from. The zero hash signifies that no conduit
* should be used (and direct approvals set on
* Consideration).
* @param recipient The intended recipient for all received items.
*
* @return A boolean indicating whether the order has been fulfilled.
*/
function _validateAndFulfillAdvancedOrder(
AdvancedOrder memory advancedOrder,
CriteriaResolver[] memory criteriaResolvers,
bytes32 fulfillerConduitKey,
address recipient
) internal returns (bool) {
// Validate the order and revert if it's invalid.
OrderValidation memory orderValidation = _validateOrder(
advancedOrder,
true
);
// Apply criteria resolvers using generated orders and details arrays.
_applyCriteriaResolversAdvanced(advancedOrder, criteriaResolvers);
// Retrieve the order parameters after applying criteria resolvers.
OrderParameters memory orderParameters = advancedOrder.parameters;
// Perform each item transfer with the appropriate fractional amount.
orderValidation.orderToExecute = _applyFractions(
orderParameters,
orderValidation.newNumerator,
orderValidation.newDenominator
);
// Declare empty bytes32 array.
bytes32[] memory priorOrderHashes = new bytes32[](0);
if (orderParameters.orderType != OrderType.CONTRACT) {
// Ensure restricted orders have valid submitter or pass zone check.
_assertRestrictedAdvancedOrderAuthorization(
advancedOrder,
orderValidation.orderToExecute,
priorOrderHashes,
orderValidation.orderHash,
orderParameters.zoneHash,
orderParameters.orderType,
orderParameters.offerer,
orderParameters.zone
);
// Update the order status to reflect the new numerator and denominator.
// Revert if the order is not valid.
_updateStatus(
orderValidation.orderHash,
orderValidation.newNumerator,
orderValidation.newDenominator,
true
);
} else {
bytes32 orderHash = _getGeneratedOrder(
orderValidation.orderToExecute,
advancedOrder.parameters,
advancedOrder.extraData,
true
);
orderValidation.orderHash = orderHash;
}
// Transfer each item contained in the order.
_transferEach(
orderParameters,
orderValidation.orderToExecute,
fulfillerConduitKey,
recipient
);
// Declare bytes32 array with this order's hash
priorOrderHashes = new bytes32[](1);
priorOrderHashes[0] = orderValidation.orderHash;
// Ensure restricted orders have valid submitter or pass zone check.
_assertRestrictedAdvancedOrderValidity(
advancedOrder,
orderValidation.orderToExecute,
priorOrderHashes,
orderValidation.orderHash,
orderParameters.zoneHash,
orderParameters.orderType,
orderParameters.offerer,
orderParameters.zone
);
// Emit an event signifying that the order has been fulfilled.
emit OrderFulfilled(
orderValidation.orderHash,
orderParameters.offerer,
orderParameters.zone,
recipient,
orderValidation.orderToExecute.spentItems,
orderValidation.orderToExecute.receivedItems
);
return true;
}
/**
* @dev Internal view function to apply a respective fraction to the
* amount being transferred on each item of an order.
*
* @param orderParameters The parameters for the fulfilled order.
* @param numerator A value indicating the portion of the order
* that should be filled.
* @param denominator A value indicating the total order size.
* @return orderToExecute Returns the order with items that are being
* transferred. This will be used for the
* OrderFulfilled Event.
*/
function _applyFractions(
OrderParameters memory orderParameters,
uint256 numerator,
uint256 denominator
) internal view returns (OrderToExecute memory orderToExecute) {
// Derive order duration, time elapsed, and time remaining.
// Store in memory to avoid stack too deep issues.
FractionData memory fractionData = FractionData(
numerator,
denominator,
0, // fulfillerConduitKey is not used here.
orderParameters.startTime,
orderParameters.endTime
);
// Create the array to store the spent items for event.
orderToExecute.spentItems = (
new SpentItem[](orderParameters.offer.length)
);
// Declare a nested scope to minimize stack depth.
{
// Iterate over each offer on the order.
for (uint256 i = 0; i < orderParameters.offer.length; ++i) {
// Retrieve the offer item.
OfferItem memory offerItem = orderParameters.offer[i];
// Offer items for the native token can not be received outside
// of a match order function except as part of a contract order.
if (
offerItem.itemType == ItemType.NATIVE &&
orderParameters.orderType != OrderType.CONTRACT
) {
revert InvalidNativeOfferItem();
}
// Apply fill fraction to derive offer item amount to transfer.
uint256 amount = _applyFraction(
offerItem.startAmount,
offerItem.endAmount,
fractionData,
false
);
// Create Spent Item for the OrderFulfilled event.
orderToExecute.spentItems[i] = SpentItem(
offerItem.itemType,
offerItem.token,
offerItem.identifierOrCriteria,
amount
);
}
}
// Create the array to store the received items for event.
orderToExecute.receivedItems = (
new ReceivedItem[](orderParameters.consideration.length)
);
// Declare a nested scope to minimize stack depth.
{
// Iterate over each consideration on the order.
for (uint256 i = 0; i < orderParameters.consideration.length; ++i) {
// Retrieve the consideration item.
ConsiderationItem memory considerationItem = (
orderParameters.consideration[i]
);
// Apply fraction & derive considerationItem amount to transfer.
uint256 amount = _applyFraction(
considerationItem.startAmount,
considerationItem.endAmount,
fractionData,
true
);
// Create Received Item from Offer item & add to structs array.
orderToExecute.receivedItems[i] = ReceivedItem(
considerationItem.itemType,
considerationItem.token,
considerationItem.identifierOrCriteria,
amount,
considerationItem.recipient
);
}
}
// Return the order to execute.
return orderToExecute;
}
/**
* @dev Internal function to transfer each item contained in a given single
* order fulfillment.
*
* @param orderParameters The parameters for the fulfilled order.
* @param orderToExecute The items that are being transferred.
* @param fulfillerConduitKey A bytes32 value indicating what conduit, if
* any, to source the fulfiller's token approvals
* from. The zero hash signifies that no conduit
* should be used (and direct approvals set on
* Consideration).
* @param recipient The intended recipient for all received items.
*/
function _transferEach(
OrderParameters memory orderParameters,
OrderToExecute memory orderToExecute,
bytes32 fulfillerConduitKey,
address recipient
) internal {
// Create the accumulator struct.
AccumulatorStruct memory accumulatorStruct;
// Get the offerer of the order.
address offerer = orderParameters.offerer;
// Get the conduitKey of the order
bytes32 conduitKey = orderParameters.conduitKey;
// Declare a nested scope to minimize stack depth.
{
// Iterate over each spent item on the order.
for (uint256 i = 0; i < orderToExecute.spentItems.length; ++i) {
// Retrieve the spent item.
SpentItem memory spentItem = orderToExecute.spentItems[i];
// Create Received Item from Spent Item for transfer.
ReceivedItem memory receivedItem = ReceivedItem(
spentItem.itemType,
spentItem.token,
spentItem.identifier,
spentItem.amount,
payable(recipient)
);
// Transfer the item from the offerer to the recipient.
_transfer(receivedItem, offerer, conduitKey, accumulatorStruct);
}
}
// Declare a nested scope to minimize stack depth.
{
// Iterate over each received item on the order.
for (uint256 i = 0; i < orderToExecute.receivedItems.length; ++i) {
// Retrieve the received item.
ReceivedItem memory receivedItem = (
orderToExecute.receivedItems[i]
);
if (receivedItem.itemType == ItemType.NATIVE) {
// Ensure that sufficient native tokens are still available.
if (receivedItem.amount > address(this).balance) {
revert InsufficientNativeTokensSupplied();
}
}
// Transfer item from caller to recipient specified by the item.
_transfer(
receivedItem,
msg.sender,
fulfillerConduitKey,
accumulatorStruct
);
}
}
// Trigger any remaining accumulated transfers via call to the conduit.
_triggerIfArmed(accumulatorStruct);
// If any native tokens remain after applying fulfillments...
if (address(this).balance != 0) {
// return them to the caller.
_transferNativeTokens(payable(msg.sender), address(this).balance);
}
}
/**
* @dev Internal pure function to convert an order to an advanced order with
* numerator and denominator of 1 and empty extraData.
*
* @param order The order to convert.
*
* @return advancedOrder The new advanced order.
*/
function _convertOrderToAdvanced(
Order calldata order
) internal pure returns (AdvancedOrder memory advancedOrder) {
// Convert to partial order (1/1 or full fill) and return new value.
advancedOrder = AdvancedOrder(
order.parameters,
1,
1,
order.signature,
""
);
}
/**
* @dev Internal pure function to convert an array of orders to an array of
* advanced orders with numerator and denominator of 1.
*
* @param orders The orders to convert.
*
* @return advancedOrders The new array of partial orders.
*/
function _convertOrdersToAdvanced(
Order[] calldata orders
) internal pure returns (AdvancedOrder[] memory advancedOrders) {
// Read the number of orders from calldata and place on the stack.
uint256 totalOrders = orders.length;
// Allocate new empty array for each partial order in memory.
advancedOrders = new AdvancedOrder[](totalOrders);
// Iterate over the given orders.
for (uint256 i = 0; i < totalOrders; ++i) {
// Convert to partial order (1/1 or full fill) and update array.
advancedOrders[i] = _convertOrderToAdvanced(orders[i]);
}
// Return the array of advanced orders.
return advancedOrders;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import { ConduitItemType } from "./ConduitEnums.sol";
/**
* @dev A ConduitTransfer is a struct that contains the information needed for a
* conduit to transfer an item from one address to another.
*/
struct ConduitTransfer {
ConduitItemType itemType;
address token;
address from;
address to;
uint256 identifier;
uint256 amount;
}
/**
* @dev A ConduitBatch1155Transfer is a struct that contains the information
* needed for a conduit to transfer a batch of ERC-1155 tokens from one
* address to another.
*/
struct ConduitBatch1155Transfer {
address token;
address from;
address to;
uint256[] ids;
uint256[] amounts;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
AdvancedOrder,
BasicOrderParameters,
CriteriaResolver,
Execution,
Fulfillment,
FulfillmentComponent,
Order,
OrderComponents
} from "../lib/ConsiderationStructs.sol";
/**
* @title SeaportInterface
* @author 0age
* @custom:version 1.6
* @notice Seaport is a generalized native token/ERC20/ERC721/ERC1155
* marketplace. It minimizes external calls to the greatest extent
* possible and provides lightweight methods for common routes as well
* as more flexible methods for composing advanced orders.
*
* @dev SeaportInterface contains all external function interfaces for Seaport.
*/
interface SeaportInterface {
/**
* @notice Fulfill an order offering an ERC721 token by supplying Ether (or
* the native token for the given chain) as consideration for the
* order. An arbitrary number of "additional recipients" may also be
* supplied which will each receive native tokens from the fulfiller
* as consideration.
*
* @param parameters Additional information on the fulfilled order. Note
* that the offerer must first approve this contract (or
* their preferred conduit if indicated by the order) for
* their offered ERC721 token to be transferred.
*
* @return fulfilled A boolean indicating whether the order has been
* successfully fulfilled.
*/
function fulfillBasicOrder(
BasicOrderParameters calldata parameters
) external payable returns (bool fulfilled);
/**
* @notice Fulfill an order with an arbitrary number of items for offer and
* consideration. Note that this function does not support
* criteria-based orders or partial filling of orders (though
* filling the remainder of a partially-filled order is supported).
*
* @param order The order to fulfill. Note that both the
* offerer and the fulfiller must first approve
* this contract (or the corresponding conduit if
* indicated) to transfer any relevant tokens on
* their behalf and that contracts must implement
* `onERC1155Received` to receive ERC1155 tokens
* as consideration.
* @param fulfillerConduitKey A bytes32 value indicating what conduit, if
* any, to source the fulfiller's token approvals
* from. The zero hash signifies that no conduit
* should be used, with direct approvals set on
* Seaport.
*
* @return fulfilled A boolean indicating whether the order has been
* successfully fulfilled.
*/
function fulfillOrder(
Order calldata order,
bytes32 fulfillerConduitKey
) external payable returns (bool fulfilled);
/**
* @notice Fill an order, fully or partially, with an arbitrary number of
* items for offer and consideration alongside criteria resolvers
* containing specific token identifiers and associated proofs.
*
* @param advancedOrder The order to fulfill along with the fraction
* of the order to attempt to fill. Note that
* both the offerer and the fulfiller must first
* approve this contract (or their preferred
* conduit if indicated by the order) to transfer
* any relevant tokens on their behalf and that
* contracts must implement `onERC1155Received`
* to receive ERC1155 tokens as consideration.
* Also note that all offer and consideration
* components must have no remainder after
* multiplication of the respective amount with
* the supplied fraction for the partial fill to
* be considered valid.
* @param criteriaResolvers An array where each element contains a
* reference to a specific offer or
* consideration, a token identifier, and a proof
* that the supplied token identifier is
* contained in the merkle root held by the item
* in question's criteria element. Note that an
* empty criteria indicates that any
* (transferable) token identifier on the token
* in question is valid and that no associated
* proof needs to be supplied.
* @param fulfillerConduitKey A bytes32 value indicating what conduit, if
* any, to source the fulfiller's token approvals
* from. The zero hash signifies that no conduit
* should be used, with direct approvals set on
* Seaport.
* @param recipient The intended recipient for all received items,
* with `address(0)` indicating that the caller
* should receive the items.
*
* @return fulfilled A boolean indicating whether the order has been
* successfully fulfilled.
*/
function fulfillAdvancedOrder(
AdvancedOrder calldata advancedOrder,
CriteriaResolver[] calldata criteriaResolvers,
bytes32 fulfillerConduitKey,
address recipient
) external payable returns (bool fulfilled);
/**
* @notice Attempt to fill a group of orders, each with an arbitrary number
* of items for offer and consideration. Any order that is not
* currently active, has already been fully filled, or has been
* cancelled will be omitted. Remaining offer and consideration
* items will then be aggregated where possible as indicated by the
* supplied offer and consideration component arrays and aggregated
* items will be transferred to the fulfiller or to each intended
* recipient, respectively. Note that a failing item transfer or an
* issue with order formatting will cause the entire batch to fail.
* Note that this function does not support criteria-based orders or
* partial filling of orders (though filling the remainder of a
* partially-filled order is supported).
*
* @param orders The orders to fulfill. Note that both
* the offerer and the fulfiller must first
* approve this contract (or the
* corresponding conduit if indicated) to
* transfer any relevant tokens on their
* behalf and that contracts must implement
* `onERC1155Received` to receive ERC1155
* tokens as consideration.
* @param offerFulfillments An array of FulfillmentComponent arrays
* indicating which offer items to attempt
* to aggregate when preparing executions.
* @param considerationFulfillments An array of FulfillmentComponent arrays
* indicating which consideration items to
* attempt to aggregate when preparing
* executions.
* @param fulfillerConduitKey A bytes32 value indicating what conduit,
* if any, to source the fulfiller's token
* approvals from. The zero hash signifies
* that no conduit should be used, with
* direct approvals set on this contract.
* @param maximumFulfilled The maximum number of orders to fulfill.
*
* @return availableOrders An array of booleans indicating if each order
* with an index corresponding to the index of the
* returned boolean was fulfillable or not.
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders. Note that unspent offer item amounts or
* native tokens will not be reflected as part of
* this array.
*/
function fulfillAvailableOrders(
Order[] calldata orders,
FulfillmentComponent[][] calldata offerFulfillments,
FulfillmentComponent[][] calldata considerationFulfillments,
bytes32 fulfillerConduitKey,
uint256 maximumFulfilled
)
external
payable
returns (bool[] memory availableOrders, Execution[] memory executions);
/**
* @notice Attempt to fill a group of orders, fully or partially, with an
* arbitrary number of items for offer and consideration per order
* alongside criteria resolvers containing specific token
* identifiers and associated proofs. Any order that is not
* currently active, has already been fully filled, or has been
* cancelled will be omitted. Remaining offer and consideration
* items will then be aggregated where possible as indicated by the
* supplied offer and consideration component arrays and aggregated
* items will be transferred to the fulfiller or to each intended
* recipient, respectively. Note that a failing item transfer or an
* issue with order formatting will cause the entire batch to fail.
*
* @param advancedOrders The orders to fulfill along with the
* fraction of those orders to attempt to
* fill. Note that both the offerer and the
* fulfiller must first approve this
* contract (or their preferred conduit if
* indicated by the order) to transfer any
* relevant tokens on their behalf and that
* contracts must implement
* `onERC1155Received` to enable receipt of
* ERC1155 tokens as consideration. Also
* note that all offer and consideration
* components must have no remainder after
* multiplication of the respective amount
* with the supplied fraction for an
* order's partial fill amount to be
* considered valid.
* @param criteriaResolvers An array where each element contains a
* reference to a specific offer or
* consideration, a token identifier, and a
* proof that the supplied token identifier
* is contained in the merkle root held by
* the item in question's criteria element.
* Note that an empty criteria indicates
* that any (transferable) token
* identifier on the token in question is
* valid and that no associated proof needs
* to be supplied.
* @param offerFulfillments An array of FulfillmentComponent arrays
* indicating which offer items to attempt
* to aggregate when preparing executions.
* @param considerationFulfillments An array of FulfillmentComponent arrays
* indicating which consideration items to
* attempt to aggregate when preparing
* executions.
* @param fulfillerConduitKey A bytes32 value indicating what conduit,
* if any, to source the fulfiller's token
* approvals from. The zero hash signifies
* that no conduit should be used, with
* direct approvals set on this contract.
* @param recipient The intended recipient for all received
* items, with `address(0)` indicating that
* the caller should receive the items.
* @param maximumFulfilled The maximum number of orders to fulfill.
*
* @return availableOrders An array of booleans indicating if each order
* with an index corresponding to the index of the
* returned boolean was fulfillable or not.
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders. Note that unspent offer item amounts or
* native tokens will not be reflected as part of
* this array.
*/
function fulfillAvailableAdvancedOrders(
AdvancedOrder[] calldata advancedOrders,
CriteriaResolver[] calldata criteriaResolvers,
FulfillmentComponent[][] calldata offerFulfillments,
FulfillmentComponent[][] calldata considerationFulfillments,
bytes32 fulfillerConduitKey,
address recipient,
uint256 maximumFulfilled
)
external
payable
returns (bool[] memory availableOrders, Execution[] memory executions);
/**
* @notice Match an arbitrary number of orders, each with an arbitrary
* number of items for offer and consideration along with a set of
* fulfillments allocating offer components to consideration
* components. Note that this function does not support
* criteria-based or partial filling of orders (though filling the
* remainder of a partially-filled order is supported). Any unspent
* offer item amounts or native tokens will be transferred to the
* caller.
*
* @param orders The orders to match. Note that both the offerer and
* fulfiller on each order must first approve this
* contract (or their conduit if indicated by the order)
* to transfer any relevant tokens on their behalf and
* each consideration recipient must implement
* `onERC1155Received` to enable ERC1155 token receipt.
* @param fulfillments An array of elements allocating offer components to
* consideration components. Note that each
* consideration component must be fully met for the
* match operation to be valid.
*
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders. Note that unspent offer item amounts or
* native tokens will not be reflected as part of this
* array.
*/
function matchOrders(
Order[] calldata orders,
Fulfillment[] calldata fulfillments
) external payable returns (Execution[] memory executions);
/**
* @notice Match an arbitrary number of full or partial orders, each with an
* arbitrary number of items for offer and consideration, supplying
* criteria resolvers containing specific token identifiers and
* associated proofs as well as fulfillments allocating offer
* components to consideration components. Any unspent offer item
* amounts will be transferred to the designated recipient (with the
* null address signifying to use the caller) and any unspent native
* tokens will be returned to the caller.
*
* @param orders The advanced orders to match. Note that both the
* offerer and fulfiller on each order must first
* approve this contract (or a preferred conduit if
* indicated by the order) to transfer any relevant
* tokens on their behalf and each consideration
* recipient must implement `onERC1155Received` in
* order to receive ERC1155 tokens. Also note that
* the offer and consideration components for each
* order must have no remainder after multiplying
* the respective amount with the supplied fraction
* in order for the group of partial fills to be
* considered valid.
* @param criteriaResolvers An array where each element contains a reference
* to a specific order as well as that order's
* offer or consideration, a token identifier, and
* a proof that the supplied token identifier is
* contained in the order's merkle root. Note that
* an empty root indicates that any (transferable)
* token identifier is valid and that no associated
* proof needs to be supplied.
* @param fulfillments An array of elements allocating offer components
* to consideration components. Note that each
* consideration component must be fully met in
* order for the match operation to be valid.
* @param recipient The intended recipient for all unspent offer
* item amounts, or the caller if the null address
* is supplied.
*
* @return executions An array of elements indicating the sequence of
* transfers performed as part of matching the given
* orders. Note that unspent offer item amounts or native
* tokens will not be reflected as part of this array.
*/
function matchAdvancedOrders(
AdvancedOrder[] calldata orders,
CriteriaResolver[] calldata criteriaResolvers,
Fulfillment[] calldata fulfillments,
address recipient
) external payable returns (Execution[] memory executions);
/**
* @notice Cancel an arbitrary number of orders. Note that only the offerer
* or the zone of a given order may cancel it. Callers should ensure
* that the intended order was cancelled by calling `getOrderStatus`
* and confirming that `isCancelled` returns `true`.
*
* @param orders The orders to cancel.
*
* @return cancelled A boolean indicating whether the supplied orders have
* been successfully cancelled.
*/
function cancel(
OrderComponents[] calldata orders
) external returns (bool cancelled);
/**
* @notice Validate an arbitrary number of orders, thereby registering their
* signatures as valid and allowing the fulfiller to skip signature
* verification on fulfillment. Note that validated orders may still
* be unfulfillable due to invalid item amounts or other factors;
* callers should determine whether validated orders are fulfillable
* by simulating the fulfillment call prior to execution. Also note
* that anyone can validate a signed order, but only the offerer can
* validate an order without supplying a signature.
*
* @param orders The orders to validate.
*
* @return validated A boolean indicating whether the supplied orders have
* been successfully validated.
*/
function validate(
Order[] calldata orders
) external returns (bool validated);
/**
* @notice Cancel all orders from a given offerer with a given zone in bulk
* by incrementing a counter. Note that only the offerer may
* increment the counter.
*
* @return newCounter The new counter.
*/
function incrementCounter() external returns (uint256 newCounter);
/**
* @notice Fulfill an order offering an ERC721 token by supplying Ether (or
* the native token for the given chain) as consideration for the
* order. An arbitrary number of "additional recipients" may also be
* supplied which will each receive native tokens from the fulfiller
* as consideration. Note that this function costs less gas than
* `fulfillBasicOrder` due to the zero bytes in the function
* selector (0x00000000) which also results in earlier function
* dispatch.
*
* @param parameters Additional information on the fulfilled order. Note
* that the offerer must first approve this contract (or
* their preferred conduit if indicated by the order) for
* their offered ERC721 token to be transferred.
*
* @return fulfilled A boolean indicating whether the order has been
* successfully fulfilled.
*/
function fulfillBasicOrder_efficient_6GL6yc(
BasicOrderParameters calldata parameters
) external payable returns (bool fulfilled);
/**
* @notice Retrieve the order hash for a given order.
*
* @param order The components of the order.
*
* @return orderHash The order hash.
*/
function getOrderHash(
OrderComponents calldata order
) external view returns (bytes32 orderHash);
/**
* @notice Retrieve the status of a given order by hash, including whether
* the order has been cancelled or validated and the fraction of the
* order that has been filled.
*
* @param orderHash The order hash in question.
*
* @return isValidated A boolean indicating whether the order in question
* has been validated (i.e. previously approved or
* partially filled).
* @return isCancelled A boolean indicating whether the order in question
* has been cancelled.
* @return totalFilled The total portion of the order that has been filled
* (i.e. the "numerator").
* @return totalSize The total size of the order that is either filled or
* unfilled (i.e. the "denominator").
*/
function getOrderStatus(
bytes32 orderHash
)
external
view
returns (
bool isValidated,
bool isCancelled,
uint256 totalFilled,
uint256 totalSize
);
/**
* @notice Retrieve the current counter for a given offerer.
*
* @param offerer The offerer in question.
*
* @return counter The current counter.
*/
function getCounter(
address offerer
) external view returns (uint256 counter);
/**
* @notice Retrieve configuration information for this contract.
*
* @return version The contract version.
* @return domainSeparator The domain separator for this contract.
* @return conduitController The conduit Controller set for this contract.
*/
function information()
external
view
returns (
string memory version,
bytes32 domainSeparator,
address conduitController
);
function getContractOffererNonce(
address contractOfferer
) external view returns (uint256 nonce);
/**
* @notice Retrieve the name of this contract.
*
* @return contractName The name of this contract.
*/
function name() external view returns (string memory contractName);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
AmountDerivationErrors
} from "seaport-types/src/interfaces/AmountDerivationErrors.sol";
import { FractionData } from "./ReferenceConsiderationStructs.sol";
/**
* @title ReferenceAmountDeriver
* @author 0age
* @notice ReferenceAmountDeriver contains view and pure functions related to
* deriving item amounts based on partial fill quantity and on linear
* interpolation based on current time when the start amount and end
* amount differ.
*/
contract ReferenceAmountDeriver is AmountDerivationErrors {
/**
* @dev Internal view function to derive the current amount of a given item
* based on the current price, the starting price, and the ending
* price. If the start and end prices differ, the current price will be
* interpolated on a linear basis.
*
* @param startAmount The starting amount of the item.
* @param endAmount The ending amount of the item.
* @param startTime The starting time of the order.
* @param endTime The end time of the order.
* @param roundUp A boolean indicating whether the resultant amount
* should be rounded up or down.
*
* @return The current amount.
*/
function _locateCurrentAmount(
uint256 startAmount,
uint256 endAmount,
uint256 startTime,
uint256 endTime,
bool roundUp
) internal view returns (uint256) {
// Only modify end amount if it doesn't already equal start amount.
if (startAmount != endAmount) {
// Leave extra amount to add for rounding at zero (i.e. round down).
uint256 extraCeiling = 0;
// Derive the duration for the order and place it on the stack.
uint256 duration = endTime - startTime;
// Derive time elapsed since the order started & place on stack.
uint256 elapsed = block.timestamp - startTime;
// Derive time remaining until order expires and place on stack.
uint256 remaining = duration - elapsed;
// If rounding up, set rounding factor to one less than denominator.
if (roundUp) {
extraCeiling = duration - 1;
}
// Aggregate new amounts weighted by time with rounding factor.
uint256 totalBeforeDivision = ((startAmount * remaining) +
(endAmount * elapsed) +
extraCeiling);
// Divide totalBeforeDivision by duration to get the new amount.
uint256 newAmount = totalBeforeDivision / duration;
// Return the current amount.
return newAmount;
}
// Return the original amount.
return endAmount;
}
/**
* @dev Internal pure function to return a fraction of a given value and to
* ensure the resultant value does not have any fractional component.
*
* @param numerator A value indicating the portion of the order that
* should be filled.
* @param denominator A value indicating the total size of the order.
* @param value The value for which to compute the fraction.
*
* @return newValue The value after applying the fraction.
*/
function _getFraction(
uint256 numerator,
uint256 denominator,
uint256 value
) internal pure returns (uint256 newValue) {
// Return value early in cases where the fraction resolves to 1.
if (numerator == denominator) {
return value;
}
// Multiply the numerator by the value and ensure no overflow occurs.
uint256 valueTimesNumerator = value * numerator;
// Divide that value by the denominator to get the new value.
newValue = valueTimesNumerator / denominator;
// Ensure that division gave a final result with no remainder.
bool exact = ((newValue * denominator) / numerator) == value;
if (!exact) {
revert InexactFraction();
}
}
/**
* @dev Internal view function to apply a fraction to a consideration
* or offer item.
*
* @param startAmount The starting amount of the item.
* @param endAmount The ending amount of the item.
* @param fractionData A struct containing the data used to apply a
* fraction to an order.
* @param roundUp A boolean indicating whether the resultant
* amount should be rounded up or down.
*
* @return amount The received item to transfer with the final amount.
*/
function _applyFraction(
uint256 startAmount,
uint256 endAmount,
FractionData memory fractionData,
bool roundUp
) internal view returns (uint256 amount) {
// If start amount equals end amount, apply fraction to end amount.
if (startAmount == endAmount) {
amount = _getFraction(
fractionData.numerator,
fractionData.denominator,
endAmount
);
} else {
// Otherwise, apply fraction to both to interpolated final amount.
amount = _locateCurrentAmount(
_getFraction(
fractionData.numerator,
fractionData.denominator,
startAmount
),
_getFraction(
fractionData.numerator,
fractionData.denominator,
endAmount
),
fractionData.startTime,
fractionData.endTime,
roundUp
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import { Side } from "../lib/ConsiderationEnums.sol";
/**
* @title FulfillmentApplicationErrors
* @author 0age
* @notice FulfillmentApplicationErrors contains errors related to fulfillment
* application and aggregation.
*/
interface FulfillmentApplicationErrors {
/**
* @dev Revert with an error when a fulfillment is provided that does not
* declare at least one component as part of a call to fulfill
* available orders.
*/
error MissingFulfillmentComponentOnAggregation(Side side);
/**
* @dev Revert with an error when a fulfillment is provided that does not
* declare at least one offer component and at least one consideration
* component.
*/
error OfferAndConsiderationRequiredOnFulfillment();
/**
* @dev Revert with an error when the initial offer item named by a
* fulfillment component does not match the type, token, identifier,
* or conduit preference of the initial consideration item.
*
* @param fulfillmentIndex The index of the fulfillment component that
* does not match the initial offer item.
*/
error MismatchedFulfillmentOfferAndConsiderationComponents(
uint256 fulfillmentIndex
);
/**
* @dev Revert with an error when an order or item index are out of range
* or a fulfillment component does not match the type, token,
* identifier, or conduit preference of the initial consideration item.
*/
error InvalidFulfillmentComponentData();
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
BasicOrderRouteType,
BasicOrderType,
ItemType,
OrderType
} from "seaport-types/src/lib/ConsiderationEnums.sol";
import {
AdditionalRecipient,
BasicOrderParameters,
ConsiderationItem,
OfferItem,
ReceivedItem,
SpentItem
} from "seaport-types/src/lib/ConsiderationStructs.sol";
import {
AccumulatorStruct,
BasicFulfillmentHashes,
FulfillmentItemTypes
} from "./ReferenceConsiderationStructs.sol";
import { ReferenceOrderValidator } from "./ReferenceOrderValidator.sol";
/**
* @title BasicOrderFulfiller
* @author 0age
* @notice BasicOrderFulfiller contains functionality for fulfilling "basic"
* orders.
*/
contract ReferenceBasicOrderFulfiller is ReferenceOrderValidator {
// Map BasicOrderType to BasicOrderRouteType
mapping(BasicOrderType => BasicOrderRouteType) internal _OrderToRouteType;
// Map BasicOrderType to OrderType
mapping(BasicOrderType => OrderType) internal _BasicOrderToOrderType;
/**
* @dev Derive and set hashes, reference chainId, and associated domain
* separator during deployment.
*
* @param conduitController A contract that deploys conduits, or proxies
* that may optionally be used to transfer approved
* ERC20/721/1155 tokens.
*/
constructor(
address conduitController
) ReferenceOrderValidator(conduitController) {
createMappings();
}
/**
* @dev Creates a mapping of BasicOrderType Enums to BasicOrderRouteType
* Enums and BasicOrderType Enums to OrderType Enums. Note that this
* is wildly inefficient, but makes the logic easier to follow when
* performing the fulfillment.
*/
function createMappings() internal {
// BasicOrderType to BasicOrderRouteType
// ETH TO ERC 721
_OrderToRouteType[
BasicOrderType.ETH_TO_ERC721_FULL_OPEN
] = BasicOrderRouteType.ETH_TO_ERC721;
_OrderToRouteType[
BasicOrderType.ETH_TO_ERC721_PARTIAL_OPEN
] = BasicOrderRouteType.ETH_TO_ERC721;
_OrderToRouteType[
BasicOrderType.ETH_TO_ERC721_FULL_RESTRICTED
] = BasicOrderRouteType.ETH_TO_ERC721;
_OrderToRouteType[
BasicOrderType.ETH_TO_ERC721_PARTIAL_RESTRICTED
] = BasicOrderRouteType.ETH_TO_ERC721;
// ETH TO ERC 1155
_OrderToRouteType[
BasicOrderType.ETH_TO_ERC1155_FULL_OPEN
] = BasicOrderRouteType.ETH_TO_ERC1155;
_OrderToRouteType[
BasicOrderType.ETH_TO_ERC1155_PARTIAL_OPEN
] = BasicOrderRouteType.ETH_TO_ERC1155;
_OrderToRouteType[
BasicOrderType.ETH_TO_ERC1155_FULL_RESTRICTED
] = BasicOrderRouteType.ETH_TO_ERC1155;
_OrderToRouteType[
BasicOrderType.ETH_TO_ERC1155_PARTIAL_RESTRICTED
] = BasicOrderRouteType.ETH_TO_ERC1155;
// ERC 20 TO ERC 721
_OrderToRouteType[
BasicOrderType.ERC20_TO_ERC721_FULL_OPEN
] = BasicOrderRouteType.ERC20_TO_ERC721;
_OrderToRouteType[
BasicOrderType.ERC20_TO_ERC721_PARTIAL_OPEN
] = BasicOrderRouteType.ERC20_TO_ERC721;
_OrderToRouteType[
BasicOrderType.ERC20_TO_ERC721_FULL_RESTRICTED
] = BasicOrderRouteType.ERC20_TO_ERC721;
_OrderToRouteType[
BasicOrderType.ERC20_TO_ERC721_PARTIAL_RESTRICTED
] = BasicOrderRouteType.ERC20_TO_ERC721;
// ERC 20 TO ERC 1155
_OrderToRouteType[
BasicOrderType.ERC20_TO_ERC1155_FULL_OPEN
] = BasicOrderRouteType.ERC20_TO_ERC1155;
_OrderToRouteType[
BasicOrderType.ERC20_TO_ERC1155_PARTIAL_OPEN
] = BasicOrderRouteType.ERC20_TO_ERC1155;
_OrderToRouteType[
BasicOrderType.ERC20_TO_ERC1155_FULL_RESTRICTED
] = BasicOrderRouteType.ERC20_TO_ERC1155;
_OrderToRouteType[
BasicOrderType.ERC20_TO_ERC1155_PARTIAL_RESTRICTED
] = BasicOrderRouteType.ERC20_TO_ERC1155;
// ERC 721 TO ERC 20
_OrderToRouteType[
BasicOrderType.ERC721_TO_ERC20_FULL_OPEN
] = BasicOrderRouteType.ERC721_TO_ERC20;
_OrderToRouteType[
BasicOrderType.ERC721_TO_ERC20_PARTIAL_OPEN
] = BasicOrderRouteType.ERC721_TO_ERC20;
_OrderToRouteType[
BasicOrderType.ERC721_TO_ERC20_FULL_RESTRICTED
] = BasicOrderRouteType.ERC721_TO_ERC20;
_OrderToRouteType[
BasicOrderType.ERC721_TO_ERC20_PARTIAL_RESTRICTED
] = BasicOrderRouteType.ERC721_TO_ERC20;
// ERC 1155 TO ERC 20
_OrderToRouteType[
BasicOrderType.ERC1155_TO_ERC20_FULL_OPEN
] = BasicOrderRouteType.ERC1155_TO_ERC20;
_OrderToRouteType[
BasicOrderType.ERC1155_TO_ERC20_PARTIAL_OPEN
] = BasicOrderRouteType.ERC1155_TO_ERC20;
_OrderToRouteType[
BasicOrderType.ERC1155_TO_ERC20_FULL_RESTRICTED
] = BasicOrderRouteType.ERC1155_TO_ERC20;
_OrderToRouteType[
BasicOrderType.ERC1155_TO_ERC20_PARTIAL_RESTRICTED
] = BasicOrderRouteType.ERC1155_TO_ERC20;
// Basic OrderType to OrderType
// FULL OPEN
_BasicOrderToOrderType[
BasicOrderType.ETH_TO_ERC721_FULL_OPEN
] = OrderType.FULL_OPEN;
_BasicOrderToOrderType[
BasicOrderType.ETH_TO_ERC1155_FULL_OPEN
] = OrderType.FULL_OPEN;
_BasicOrderToOrderType[
BasicOrderType.ERC20_TO_ERC721_FULL_OPEN
] = OrderType.FULL_OPEN;
_BasicOrderToOrderType[
BasicOrderType.ERC20_TO_ERC1155_FULL_OPEN
] = OrderType.FULL_OPEN;
_BasicOrderToOrderType[
BasicOrderType.ERC721_TO_ERC20_FULL_OPEN
] = OrderType.FULL_OPEN;
_BasicOrderToOrderType[
BasicOrderType.ERC1155_TO_ERC20_FULL_OPEN
] = OrderType.FULL_OPEN;
// PARTIAL OPEN
_BasicOrderToOrderType[
BasicOrderType.ETH_TO_ERC721_PARTIAL_OPEN
] = OrderType.PARTIAL_OPEN;
_BasicOrderToOrderType[
BasicOrderType.ETH_TO_ERC1155_PARTIAL_OPEN
] = OrderType.PARTIAL_OPEN;
_BasicOrderToOrderType[
BasicOrderType.ERC20_TO_ERC721_PARTIAL_OPEN
] = OrderType.PARTIAL_OPEN;
_BasicOrderToOrderType[
BasicOrderType.ERC20_TO_ERC1155_PARTIAL_OPEN
] = OrderType.PARTIAL_OPEN;
_BasicOrderToOrderType[
BasicOrderType.ERC721_TO_ERC20_PARTIAL_OPEN
] = OrderType.PARTIAL_OPEN;
_BasicOrderToOrderType[
BasicOrderType.ERC1155_TO_ERC20_PARTIAL_OPEN
] = OrderType.PARTIAL_OPEN;
// FULL RESTRICTED
_BasicOrderToOrderType[
BasicOrderType.ETH_TO_ERC721_FULL_RESTRICTED
] = OrderType.FULL_RESTRICTED;
_BasicOrderToOrderType[
BasicOrderType.ETH_TO_ERC1155_FULL_RESTRICTED
] = OrderType.FULL_RESTRICTED;
_BasicOrderToOrderType[
BasicOrderType.ERC20_TO_ERC721_FULL_RESTRICTED
] = OrderType.FULL_RESTRICTED;
_BasicOrderToOrderType[
BasicOrderType.ERC20_TO_ERC1155_FULL_RESTRICTED
] = OrderType.FULL_RESTRICTED;
_BasicOrderToOrderType[
BasicOrderType.ERC721_TO_ERC20_FULL_RESTRICTED
] = OrderType.FULL_RESTRICTED;
_BasicOrderToOrderType[
BasicOrderType.ERC1155_TO_ERC20_FULL_RESTRICTED
] = OrderType.FULL_RESTRICTED;
// PARTIAL RESTRICTED
_BasicOrderToOrderType[
BasicOrderType.ETH_TO_ERC721_PARTIAL_RESTRICTED
] = OrderType.PARTIAL_RESTRICTED;
_BasicOrderToOrderType[
BasicOrderType.ETH_TO_ERC1155_PARTIAL_RESTRICTED
] = OrderType.PARTIAL_RESTRICTED;
_BasicOrderToOrderType[
BasicOrderType.ERC20_TO_ERC721_PARTIAL_RESTRICTED
] = OrderType.PARTIAL_RESTRICTED;
_BasicOrderToOrderType[
BasicOrderType.ERC20_TO_ERC1155_PARTIAL_RESTRICTED
] = OrderType.PARTIAL_RESTRICTED;
_BasicOrderToOrderType[
BasicOrderType.ERC721_TO_ERC20_PARTIAL_RESTRICTED
] = OrderType.PARTIAL_RESTRICTED;
_BasicOrderToOrderType[
BasicOrderType.ERC1155_TO_ERC20_PARTIAL_RESTRICTED
] = OrderType.PARTIAL_RESTRICTED;
}
/**
* @dev Internal function to fulfill an order offering an ERC20, ERC721, or
* ERC1155 item by supplying Ether (or other native tokens), ERC20
* tokens, an ERC721 item, or an ERC1155 item as consideration. Six
* permutations are supported: Native token to ERC721, Native token to
* ERC1155, ERC20 to ERC721, ERC20 to ERC1155, ERC721 to ERC20, and
* ERC1155 to ERC20 (with native tokens supplied as msg.value). For an
* order to be eligible for fulfillment via this method, it must
* contain a single offer item (though that item may have a greater
* amount if the item is not an ERC721). An arbitrary number of
* "additional recipients" may also be supplied which will each receive
* native tokens or ERC20 items from the fulfiller as consideration.
* Refer to the documentation for a more comprehensive summary of how
* to utilize with this method and what orders are compatible with it.
*
* @param parameters Additional information on the fulfilled order. Note
* that the offerer and the fulfiller must first approve
* this contract (or their chosen conduit if indicated)
* before any tokens can be transferred. Also note that
* contract recipients of ERC1155 consideration items must
* implement `onERC1155Received` in order to receive those
* items.
*
* @return A boolean indicating whether the order has been fulfilled.
*/
function _validateAndFulfillBasicOrder(
BasicOrderParameters calldata parameters
) internal returns (bool) {
// Determine the basic order route type from the basic order type.
BasicOrderRouteType route;
{
BasicOrderType basicType = parameters.basicOrderType;
route = _OrderToRouteType[basicType];
}
// Determine the order type from the basic order type.
OrderType orderType;
{
BasicOrderType basicType = parameters.basicOrderType;
orderType = _BasicOrderToOrderType[basicType];
}
// Declare additional recipient item type to derive from the route type.
ItemType additionalRecipientsItemType;
if (
route == BasicOrderRouteType.ETH_TO_ERC721 ||
route == BasicOrderRouteType.ETH_TO_ERC1155
) {
additionalRecipientsItemType = ItemType.NATIVE;
} else {
additionalRecipientsItemType = ItemType.ERC20;
}
// Revert if msg.value was not supplied as part of a payable route.
if (msg.value == 0 && additionalRecipientsItemType == ItemType.NATIVE) {
revert InvalidMsgValue(msg.value);
}
// Revert if msg.value was supplied as part of a non-payable route.
if (msg.value != 0 && additionalRecipientsItemType == ItemType.ERC20) {
revert InvalidMsgValue(msg.value);
}
// Determine the token that additional recipients should have set.
address additionalRecipientsToken;
if (
route == BasicOrderRouteType.ERC721_TO_ERC20 ||
route == BasicOrderRouteType.ERC1155_TO_ERC20
) {
additionalRecipientsToken = parameters.offerToken;
} else {
additionalRecipientsToken = parameters.considerationToken;
}
// Determine the item type for received items.
ItemType receivedItemType;
if (
route == BasicOrderRouteType.ETH_TO_ERC721 ||
route == BasicOrderRouteType.ETH_TO_ERC1155
) {
receivedItemType = ItemType.NATIVE;
} else if (
route == BasicOrderRouteType.ERC20_TO_ERC721 ||
route == BasicOrderRouteType.ERC20_TO_ERC1155
) {
receivedItemType = ItemType.ERC20;
} else if (route == BasicOrderRouteType.ERC721_TO_ERC20) {
receivedItemType = ItemType.ERC721;
} else {
receivedItemType = ItemType.ERC1155;
}
// Determine the item type for the offered item.
ItemType offeredItemType;
if (
route == BasicOrderRouteType.ERC721_TO_ERC20 ||
route == BasicOrderRouteType.ERC1155_TO_ERC20
) {
offeredItemType = ItemType.ERC20;
} else if (
route == BasicOrderRouteType.ETH_TO_ERC721 ||
route == BasicOrderRouteType.ERC20_TO_ERC721
) {
offeredItemType = ItemType.ERC721;
} else {
offeredItemType = ItemType.ERC1155;
}
// Derive & validate order using parameters and update order status.
bytes32 orderHash = _prepareBasicFulfillment(
parameters,
orderType,
receivedItemType,
additionalRecipientsItemType,
additionalRecipientsToken,
offeredItemType
);
// Determine conduitKey argument used by transfer functions.
bytes32 conduitKey;
if (
route == BasicOrderRouteType.ERC721_TO_ERC20 ||
route == BasicOrderRouteType.ERC1155_TO_ERC20
) {
conduitKey = parameters.fulfillerConduitKey;
} else {
conduitKey = parameters.offererConduitKey;
}
// Check for dirtied unused parameters.
if (
((route == BasicOrderRouteType.ETH_TO_ERC721 ||
route == BasicOrderRouteType.ETH_TO_ERC1155) &&
(uint160(parameters.considerationToken) |
parameters.considerationIdentifier) !=
0) ||
((route == BasicOrderRouteType.ERC20_TO_ERC721 ||
route == BasicOrderRouteType.ERC20_TO_ERC1155) &&
parameters.considerationIdentifier != 0) ||
((route == BasicOrderRouteType.ERC721_TO_ERC20 ||
route == BasicOrderRouteType.ERC1155_TO_ERC20) &&
parameters.offerIdentifier != 0)
) {
revert UnusedItemParameters();
}
// Declare transfer accumulator that will collect transfers that can be
// bundled into a single call to their associated conduit.
AccumulatorStruct memory accumulatorStruct;
// Transfer tokens based on the route.
if (route == BasicOrderRouteType.ETH_TO_ERC721) {
// Transfer ERC721 to caller using offerer's conduit if applicable.
_transferERC721(
parameters.offerToken,
parameters.offerer,
msg.sender,
parameters.offerIdentifier,
parameters.offerAmount,
conduitKey,
accumulatorStruct
);
// Transfer native to recipients, return excess to caller & wrap up.
_transferEthAndFinalize(parameters.considerationAmount, parameters);
} else if (route == BasicOrderRouteType.ETH_TO_ERC1155) {
// Transfer ERC1155 to caller using offerer's conduit if applicable.
_transferERC1155(
parameters.offerToken,
parameters.offerer,
msg.sender,
parameters.offerIdentifier,
parameters.offerAmount,
conduitKey,
accumulatorStruct
);
// Transfer native to recipients, return excess to caller & wrap up.
_transferEthAndFinalize(parameters.considerationAmount, parameters);
} else if (route == BasicOrderRouteType.ERC20_TO_ERC721) {
// Transfer ERC721 to caller using offerer's conduit if applicable.
_transferERC721(
parameters.offerToken,
parameters.offerer,
msg.sender,
parameters.offerIdentifier,
parameters.offerAmount,
conduitKey,
accumulatorStruct
);
// Transfer ERC20 tokens to all recipients and wrap up.
_transferERC20AndFinalize(
msg.sender,
parameters.offerer,
parameters.considerationToken,
parameters.considerationAmount,
parameters,
false, // Send full amount indicated by all consideration items.
accumulatorStruct
);
} else if (route == BasicOrderRouteType.ERC20_TO_ERC1155) {
// Transfer ERC1155 to caller using offerer's conduit if applicable.
_transferERC1155(
parameters.offerToken,
parameters.offerer,
msg.sender,
parameters.offerIdentifier,
parameters.offerAmount,
conduitKey,
accumulatorStruct
);
// Transfer ERC20 tokens to all recipients and wrap up.
_transferERC20AndFinalize(
msg.sender,
parameters.offerer,
parameters.considerationToken,
parameters.considerationAmount,
parameters,
false, // Send full amount indicated by all consideration items.
accumulatorStruct
);
} else if (route == BasicOrderRouteType.ERC721_TO_ERC20) {
// Transfer ERC721 to offerer using caller's conduit if applicable.
_transferERC721(
parameters.considerationToken,
msg.sender,
parameters.offerer,
parameters.considerationIdentifier,
parameters.considerationAmount,
conduitKey,
accumulatorStruct
);
// Transfer ERC20 tokens to all recipients and wrap up.
_transferERC20AndFinalize(
parameters.offerer,
msg.sender,
parameters.offerToken,
parameters.offerAmount,
parameters,
true, // Reduce amount sent to fulfiller by additional amounts.
accumulatorStruct
);
} else {
// route == BasicOrderRouteType.ERC1155_TO_ERC20
// Transfer ERC1155 to offerer using caller's conduit if applicable.
_transferERC1155(
parameters.considerationToken,
msg.sender,
parameters.offerer,
parameters.considerationIdentifier,
parameters.considerationAmount,
conduitKey,
accumulatorStruct
);
// Transfer ERC20 tokens to all recipients and wrap up.
_transferERC20AndFinalize(
parameters.offerer,
msg.sender,
parameters.offerToken,
parameters.offerAmount,
parameters,
true, // Reduce amount sent to fulfiller by additional amounts.
accumulatorStruct
);
}
// Trigger any remaining accumulated transfers via call to the conduit.
_triggerIfArmed(accumulatorStruct);
// Determine whether order is restricted and, if so, that it is valid.
_assertRestrictedBasicOrderValidity(
orderHash,
orderType,
parameters,
offeredItemType,
receivedItemType
);
return true;
}
/**
* @dev Internal function to calculate the order hash.
*
* @param hashes The array of offerItems and receivedItems
* hashes.
* @param parameters The parameters of the basic order.
* @param fulfillmentItemTypes The fulfillment's item type.
*
* @return orderHash The order hash.
*/
function _hashOrder(
BasicFulfillmentHashes memory hashes,
BasicOrderParameters calldata parameters,
FulfillmentItemTypes memory fulfillmentItemTypes
) internal view returns (bytes32 orderHash) {
// Read offerer's current counter from storage and place on the stack.
uint256 counter = _getCounter(parameters.offerer);
// Hash the contents to get the orderHash
orderHash = keccak256(
abi.encode(
hashes.typeHash,
parameters.offerer,
parameters.zone,
hashes.offerItemsHash,
hashes.receivedItemsHash,
fulfillmentItemTypes.orderType,
parameters.startTime,
parameters.endTime,
parameters.zoneHash,
parameters.salt,
parameters.offererConduitKey,
counter
)
);
}
/**
* @dev Internal function to prepare fulfillment of a basic order. This
* calculates the order hash, emits an OrderFulfilled event, and
* asserts basic order validity.
*
* @param parameters The parameters of the basic order.
* @param orderType The order type.
* @param receivedItemType The item type of the initial
* consideration item on the order.
* @param additionalRecipientsItemType The item type of any additional
* consideration item on the order.
* @param additionalRecipientsToken The ERC20 token contract address (if
* applicable) for any additional
* consideration item on the order.
* @param offeredItemType The item type of the offered item on
* the order.
*
* @return orderHash The calculated order hash.
*/
function _prepareBasicFulfillment(
BasicOrderParameters calldata parameters,
OrderType orderType,
ItemType receivedItemType,
ItemType additionalRecipientsItemType,
address additionalRecipientsToken,
ItemType offeredItemType
) internal returns (bytes32 orderHash) {
// Ensure current timestamp falls between order start time and end time.
_verifyTime(parameters.startTime, parameters.endTime, true);
// Verify that calldata offsets for all dynamic types were produced by
// default encoding. This is only required on the optimized contract,
// but is included here to maintain parity.
_assertValidBasicOrderParameters();
// Ensure supplied consideration array length is not less than original.
_assertConsiderationLengthIsNotLessThanOriginalConsiderationLength(
parameters.additionalRecipients.length,
parameters.totalOriginalAdditionalRecipients
);
// Memory to store hashes.
BasicFulfillmentHashes memory hashes;
// Store ItemType/Token parameters in a struct in memory to avoid stack
// issues.
FulfillmentItemTypes memory fulfillmentItemTypes = FulfillmentItemTypes(
orderType,
receivedItemType,
additionalRecipientsItemType,
additionalRecipientsToken,
offeredItemType
);
// Array of Received Items for use with OrderFulfilled event.
ReceivedItem[] memory consideration = new ReceivedItem[](
parameters.additionalRecipients.length + 1
);
{
// Load consideration item typehash from runtime and place on stack.
hashes.typeHash = _CONSIDERATION_ITEM_TYPEHASH;
// Create Consideration item.
ConsiderationItem memory primaryConsiderationItem = (
ConsiderationItem(
fulfillmentItemTypes.receivedItemType,
parameters.considerationToken,
parameters.considerationIdentifier,
parameters.considerationAmount,
parameters.considerationAmount,
parameters.offerer
)
);
// Array of all consideration item hashes.
hashes.considerationHashes = new bytes32[](
parameters.totalOriginalAdditionalRecipients + 1
);
// Hash contents.
hashes.considerationHashes[0] = keccak256(
abi.encode(
hashes.typeHash,
primaryConsiderationItem.itemType,
primaryConsiderationItem.token,
primaryConsiderationItem.identifierOrCriteria,
primaryConsiderationItem.startAmount,
primaryConsiderationItem.endAmount,
primaryConsiderationItem.recipient
)
);
// Declare memory for additionalReceivedItem and
// additionalRecipientItem.
ReceivedItem memory additionalReceivedItem;
ConsiderationItem memory additionalRecipientItem;
// Create Received item.
ReceivedItem memory primaryReceivedItem = ReceivedItem(
fulfillmentItemTypes.receivedItemType,
primaryConsiderationItem.token,
primaryConsiderationItem.identifierOrCriteria,
primaryConsiderationItem.endAmount,
primaryConsiderationItem.recipient
);
// Add the Received item to the
// OrderFulfilled ReceivedItem[].
consideration[0] = primaryReceivedItem;
/** Loop through all additionalRecipients, to generate
* ReceivedItems for OrderFulfilled Event and
* ConsiderationItems for hashing.
*/
for (
uint256 recipientCount = 0;
recipientCount < parameters.totalOriginalAdditionalRecipients;
++recipientCount
) {
// Get the next additionalRecipient.
AdditionalRecipient memory additionalRecipient = (
parameters.additionalRecipients[recipientCount]
);
// Create a Received item for each additional recipients.
additionalReceivedItem = ReceivedItem(
fulfillmentItemTypes.additionalRecipientsItemType,
fulfillmentItemTypes.additionalRecipientsToken,
0,
additionalRecipient.amount,
additionalRecipient.recipient
);
// Add additional Received items to the
// OrderFulfilled ReceivedItem[].
consideration[recipientCount + 1] = additionalReceivedItem;
// Create a new consideration item for each additional
// recipient.
additionalRecipientItem = ConsiderationItem(
fulfillmentItemTypes.additionalRecipientsItemType,
fulfillmentItemTypes.additionalRecipientsToken,
0,
additionalRecipient.amount,
additionalRecipient.amount,
additionalRecipient.recipient
);
// Calculate the EIP712 ConsiderationItem hash for
// each additional recipients.
hashes.considerationHashes[recipientCount + 1] = keccak256(
abi.encode(
hashes.typeHash,
additionalRecipientItem.itemType,
additionalRecipientItem.token,
additionalRecipientItem.identifierOrCriteria,
additionalRecipientItem.startAmount,
additionalRecipientItem.endAmount,
additionalRecipientItem.recipient
)
);
}
/**
* The considerationHashes array now contains
* all consideration Item hashes.
*
* The consideration array now contains all received
* items excluding tips for OrderFulfilled Event.
*/
// Get hash of all consideration items.
hashes.receivedItemsHash = keccak256(
abi.encodePacked(hashes.considerationHashes)
);
// Get remainder of additionalRecipients for tips.
for (
uint256 additionalTips = parameters
.totalOriginalAdditionalRecipients;
additionalTips < parameters.additionalRecipients.length;
++additionalTips
) {
// Get the next additionalRecipient.
AdditionalRecipient memory additionalRecipient = (
parameters.additionalRecipients[additionalTips]
);
// Create the ReceivedItem.
additionalReceivedItem = ReceivedItem(
fulfillmentItemTypes.additionalRecipientsItemType,
fulfillmentItemTypes.additionalRecipientsToken,
0,
additionalRecipient.amount,
additionalRecipient.recipient
);
// Add additional received items to the
// OrderFulfilled ReceivedItem[].
consideration[additionalTips + 1] = additionalReceivedItem;
}
}
// Now let's handle the offer side.
// Write the offer to the Event SpentItem array.
SpentItem[] memory offer = new SpentItem[](1);
{
// Place offer item typehash on the stack.
hashes.typeHash = _OFFER_ITEM_TYPEHASH;
// Create Spent item.
SpentItem memory offerItem = SpentItem(
fulfillmentItemTypes.offeredItemType,
parameters.offerToken,
parameters.offerIdentifier,
parameters.offerAmount
);
// Add the offer item to the SpentItem array.
offer[0] = offerItem;
// Get the hash of the Spent item, treated as an Offer item.
bytes32[1] memory offerItemHashes = [
keccak256(
abi.encode(
hashes.typeHash,
offerItem.itemType,
offerItem.token,
offerItem.identifier,
offerItem.amount,
// Assembly uses OfferItem instead of SpentItem.
offerItem.amount
)
)
];
// Get hash of all Spent items.
hashes.offerItemsHash = keccak256(
abi.encodePacked(offerItemHashes)
);
}
{
// Create the OrderComponent in order to derive
// the orderHash.
// Load order typehash from runtime code and place on stack.
hashes.typeHash = _ORDER_TYPEHASH;
// Derive the order hash.
hashes.orderHash = _hashOrder(
hashes,
parameters,
fulfillmentItemTypes
);
// Emit an event signifying that the order has been fulfilled.
emit OrderFulfilled(
hashes.orderHash,
parameters.offerer,
parameters.zone,
msg.sender,
offer,
consideration
);
}
// Determine whether order is restricted and, if so, that it is valid.
_assertRestrictedBasicOrderAuthorization(
hashes.orderHash,
orderType,
parameters,
offeredItemType,
receivedItemType
);
// Verify and update the status of the derived order.
_validateBasicOrderAndUpdateStatus(
hashes.orderHash,
parameters.offerer,
parameters.signature
);
// Return the derived order hash.
return hashes.orderHash;
}
/**
* @dev Internal function to transfer Ether (or other native tokens) to a
* given recipient as part of basic order fulfillment. Note that
* proxies are not utilized for native tokens as the transferred amount
* must be provided as msg.value.
*
* @param amount The amount to transfer.
* @param parameters The parameters of the basic order in question.
*/
function _transferEthAndFinalize(
uint256 amount,
BasicOrderParameters calldata parameters
) internal {
// Put native token value supplied by the caller on the stack.
uint256 nativeTokensRemaining = msg.value;
// Iterate over each additional recipient.
for (uint256 i = 0; i < parameters.additionalRecipients.length; ++i) {
// Retrieve the additional recipient.
AdditionalRecipient calldata additionalRecipient = (
parameters.additionalRecipients[i]
);
// Read native token amount to transfer to recipient & put on stack.
uint256 additionalRecipientAmount = additionalRecipient.amount;
// Ensure that sufficient native tokens are available.
if (additionalRecipientAmount > nativeTokensRemaining) {
revert InsufficientNativeTokensSupplied();
}
// Transfer native token to the additional recipient.
_transferNativeTokens(
additionalRecipient.recipient,
additionalRecipientAmount
);
// Reduce native token value available.
nativeTokensRemaining -= additionalRecipientAmount;
}
// Ensure that sufficient native token is still available.
if (amount > nativeTokensRemaining) {
revert InsufficientNativeTokensSupplied();
}
// Transfer native token to the offerer.
_transferNativeTokens(parameters.offerer, amount);
// If any native token remains after transfers, return it to the caller.
if (nativeTokensRemaining > amount) {
// Transfer remaining native token to the caller.
_transferNativeTokens(
payable(msg.sender),
nativeTokensRemaining - amount
);
}
}
/**
* @dev Internal function to transfer ERC20 tokens to a given recipient as
* part of basic order fulfillment. Note that proxies are not utilized
* for ERC20 tokens.
*
* @param from The originator of the ERC20 token transfer.
* @param to The recipient of the ERC20 token transfer.
* @param erc20Token The ERC20 token to transfer.
* @param amount The amount of ERC20 tokens to transfer.
* @param parameters The parameters of the order.
* @param fromOfferer Whether to decrement amount from the
* offered amount.
* @param accumulatorStruct A struct containing conduit transfer data
* and its corresponding conduitKey.
*/
function _transferERC20AndFinalize(
address from,
address to,
address erc20Token,
uint256 amount,
BasicOrderParameters calldata parameters,
bool fromOfferer,
AccumulatorStruct memory accumulatorStruct
) internal {
// Determine the appropriate conduit to utilize.
bytes32 conduitKey;
if (fromOfferer) {
conduitKey = parameters.offererConduitKey;
} else {
conduitKey = parameters.fulfillerConduitKey;
}
// Iterate over each additional recipient.
for (uint256 i = 0; i < parameters.additionalRecipients.length; ++i) {
// Retrieve the additional recipient.
AdditionalRecipient calldata additionalRecipient = (
parameters.additionalRecipients[i]
);
// Decrement the amount to transfer to fulfiller if indicated.
if (fromOfferer) {
amount -= additionalRecipient.amount;
}
// Transfer ERC20 tokens to additional recipient given approval.
_transferERC20(
erc20Token,
from,
additionalRecipient.recipient,
additionalRecipient.amount,
conduitKey,
accumulatorStruct
);
}
// Transfer ERC20 token amount (from account must have proper approval).
_transferERC20(
erc20Token,
from,
to,
amount,
conduitKey,
accumulatorStruct
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @title TokenTransferrerErrors
*/
interface TokenTransferrerErrors {
/**
* @dev Revert with an error when an ERC721 transfer with amount other than
* one is attempted.
*
* @param amount The amount of the ERC721 tokens to transfer.
*/
error InvalidERC721TransferAmount(uint256 amount);
/**
* @dev Revert with an error when attempting to fulfill an order where an
* item has an amount of zero.
*/
error MissingItemAmount();
/**
* @dev Revert with an error when attempting to fulfill an order where an
* item has unused parameters. This includes both the token and the
* identifier parameters for native transfers as well as the identifier
* parameter for ERC20 transfers. Note that the conduit does not
* perform this check, leaving it up to the calling channel to enforce
* when desired.
*/
error UnusedItemParameters();
/**
* @dev Revert with an error when an ERC20, ERC721, or ERC1155 token
* transfer reverts.
*
* @param token The token for which the transfer was attempted.
* @param from The source of the attempted transfer.
* @param to The recipient of the attempted transfer.
* @param identifier The identifier for the attempted transfer.
* @param amount The amount for the attempted transfer.
*/
error TokenTransferGenericFailure(
address token,
address from,
address to,
uint256 identifier,
uint256 amount
);
/**
* @dev Revert with an error when a batch ERC1155 token transfer reverts.
*
* @param token The token for which the transfer was attempted.
* @param from The source of the attempted transfer.
* @param to The recipient of the attempted transfer.
* @param identifiers The identifiers for the attempted transfer.
* @param amounts The amounts for the attempted transfer.
*/
error ERC1155BatchTransferGenericFailure(
address token,
address from,
address to,
uint256[] identifiers,
uint256[] amounts
);
/**
* @dev Revert with an error when an ERC20 token transfer returns a falsey
* value.
*
* @param token The token for which the ERC20 transfer was attempted.
* @param from The source of the attempted ERC20 transfer.
* @param to The recipient of the attempted ERC20 transfer.
* @param amount The amount for the attempted ERC20 transfer.
*/
error BadReturnValueFromERC20OnTransfer(
address token,
address from,
address to,
uint256 amount
);
/**
* @dev Revert with an error when an account being called as an assumed
* contract does not have code and returns no data.
*
* @param account The account that should contain code.
*/
error NoContract(address account);
/**
* @dev Revert with an error when attempting to execute an 1155 batch
* transfer using calldata not produced by default ABI encoding or with
* different lengths for ids and amounts arrays.
*/
error Invalid1155BatchTransferEncoding();
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ItemType,
OrderType,
Side
} from "seaport-types/src/lib/ConsiderationEnums.sol";
import {
AdvancedOrder,
ConsiderationItem,
CriteriaResolver,
OfferItem,
OrderParameters,
ReceivedItem,
SpentItem
} from "seaport-types/src/lib/ConsiderationStructs.sol";
import { OrderToExecute } from "./ReferenceConsiderationStructs.sol";
import {
CriteriaResolutionErrors
} from "seaport-types/src/interfaces/CriteriaResolutionErrors.sol";
/**
* @title CriteriaResolution
* @author 0age
* @notice CriteriaResolution contains a collection of pure functions related to
* resolving criteria-based items.
*/
contract ReferenceCriteriaResolution is CriteriaResolutionErrors {
/**
* @dev Internal pure function to apply criteria resolvers containing
* specific token identifiers and associated proofs to order items.
*
* @param ordersToExecute The orders to apply criteria resolvers to.
* @param criteriaResolvers An array where each element contains a
* reference to a specific order as well as that
* order's offer or consideration, a token
* identifier, and a proof that the supplied token
* identifier is contained in the order's merkle
* root. Note that a root of zero indicates that
* any transferable token identifier is valid and
* that no proof needs to be supplied.
*/
function _applyCriteriaResolvers(
AdvancedOrder[] memory advancedOrders,
OrderToExecute[] memory ordersToExecute,
CriteriaResolver[] memory criteriaResolvers
) internal pure {
// Retrieve length of criteria resolvers array and place on stack.
uint256 arraySize = criteriaResolvers.length;
// Iterate over each criteria resolver.
for (uint256 i = 0; i < arraySize; ++i) {
// Retrieve the criteria resolver.
CriteriaResolver memory criteriaResolver = (criteriaResolvers[i]);
// Read the order index from memory and place it on the stack.
uint256 orderIndex = criteriaResolver.orderIndex;
// Ensure that the order index is in range.
if (orderIndex >= ordersToExecute.length) {
revert OrderCriteriaResolverOutOfRange(criteriaResolver.side);
}
// Skip criteria resolution for order if not fulfilled.
if (ordersToExecute[orderIndex].numerator == 0) {
continue;
}
// Read component index from memory and place it on the stack.
uint256 componentIndex = criteriaResolver.index;
// Declare values for item's type and criteria.
ItemType itemType;
uint256 identifierOrCriteria;
// If the criteria resolver refers to an offer item...
if (criteriaResolver.side == Side.OFFER) {
SpentItem[] memory spentItems = ordersToExecute[orderIndex]
.spentItems;
// Ensure that the component index is in range.
if (componentIndex >= spentItems.length) {
revert OfferCriteriaResolverOutOfRange();
}
// Retrieve relevant item using component index.
SpentItem memory offer = (spentItems[componentIndex]);
// Read item type and criteria from memory & place on stack.
itemType = offer.itemType;
identifierOrCriteria = offer.identifier;
// Optimistically update item type to remove criteria usage.
if (itemType == ItemType.ERC721_WITH_CRITERIA) {
offer.itemType = ItemType.ERC721;
} else {
offer.itemType = ItemType.ERC1155;
}
// Optimistically update identifier w/ supplied identifier.
offer.identifier = criteriaResolver.identifier;
} else {
// Otherwise, the resolver refers to a consideration item.
// Retrieve relevant item using order index.
ReceivedItem[] memory receivedItems = ordersToExecute[
orderIndex
].receivedItems;
// Ensure that the component index is in range.
if (componentIndex >= receivedItems.length) {
revert ConsiderationCriteriaResolverOutOfRange();
}
// Retrieve relevant item using component index.
ReceivedItem memory consideration = (
receivedItems[componentIndex]
);
// Read item type and criteria from memory & place on stack.
itemType = consideration.itemType;
identifierOrCriteria = consideration.identifier;
// Optimistically update item type to remove criteria usage.
if (itemType == ItemType.ERC721_WITH_CRITERIA) {
consideration.itemType = ItemType.ERC721;
} else {
consideration.itemType = ItemType.ERC1155;
}
// Optimistically update identifier w/ supplied identifier.
consideration.identifier = (criteriaResolver.identifier);
}
// Ensure the specified item type indicates criteria usage.
if (!_isItemWithCriteria(itemType)) {
revert CriteriaNotEnabledForItem();
}
// If criteria is not 0 (i.e. a collection-wide criteria item)...
if (identifierOrCriteria != uint256(0)) {
// Verify identifier inclusion in criteria root using proof.
_verifyProof(
criteriaResolver.identifier,
identifierOrCriteria,
criteriaResolver.criteriaProof
);
} else if (criteriaResolver.criteriaProof.length != 0) {
// Revert if a proof is supplied for a collection-wide item.
revert InvalidProof();
}
}
// Retrieve length of orders array and place on stack.
arraySize = ordersToExecute.length;
// Iterate over each order to execute.
for (uint256 i = 0; i < arraySize; ++i) {
// Retrieve the order to execute.
OrderToExecute memory orderToExecute = ordersToExecute[i];
// Read offer length from memory and place on stack.
uint256 totalItems = orderToExecute.spentItems.length;
// Skip criteria resolution for order if not fulfilled.
if (orderToExecute.numerator == 0) {
continue;
}
// Iterate over each offer item on the order.
for (uint256 j = 0; j < totalItems; ++j) {
// Ensure item type no longer indicates criteria usage.
if (
_isItemWithCriteria(orderToExecute.spentItems[j].itemType)
) {
if (
advancedOrders[i].parameters.orderType !=
OrderType.CONTRACT ||
orderToExecute.spentItems[j].identifier != 0
) {
revert UnresolvedOfferCriteria(i, j);
}
}
}
// Read consideration length from memory and place on stack.
totalItems = (orderToExecute.receivedItems.length);
// Iterate over each consideration item on the order.
for (uint256 j = 0; j < totalItems; ++j) {
// Ensure item type no longer indicates criteria usage.
if (
_isItemWithCriteria(
orderToExecute.receivedItems[j].itemType
)
) {
if (
advancedOrders[i].parameters.orderType !=
OrderType.CONTRACT ||
orderToExecute.receivedItems[j].identifier != 0
) {
revert UnresolvedConsiderationCriteria(i, j);
}
}
}
}
}
/**
* @dev Internal pure function to apply criteria resolvers containing
* specific token identifiers and associated proofs to order items.
*
* @param advancedOrder The order to apply criteria resolvers to.
* @param criteriaResolvers An array where each element contains a
* reference to a specific order as well as that
* order's offer or consideration, a token
* identifier, and a proof that the supplied token
* identifier is contained in the order's merkle
* root. Note that a root of zero indicates that
* any transferable token identifier is valid and
* that no proof needs to be supplied.
*/
function _applyCriteriaResolversAdvanced(
AdvancedOrder memory advancedOrder,
CriteriaResolver[] memory criteriaResolvers
) internal pure {
// Retrieve length of criteria resolvers array and place on stack.
uint256 arraySize = criteriaResolvers.length;
// Retrieve the parameters for the order.
OrderParameters memory orderParameters = (advancedOrder.parameters);
// Iterate over each criteria resolver.
for (uint256 i = 0; i < arraySize; ++i) {
// Retrieve the criteria resolver.
CriteriaResolver memory criteriaResolver = (criteriaResolvers[i]);
// Read the order index from memory and place it on the stack.
uint256 orderIndex = criteriaResolver.orderIndex;
if (orderIndex != 0) {
revert OrderCriteriaResolverOutOfRange(criteriaResolver.side);
}
// Read component index from memory and place it on the stack.
uint256 componentIndex = criteriaResolver.index;
// Declare values for item's type and criteria.
ItemType itemType;
uint256 identifierOrCriteria;
// If the criteria resolver refers to an offer item...
if (criteriaResolver.side == Side.OFFER) {
// Ensure that the component index is in range.
if (componentIndex >= orderParameters.offer.length) {
revert OfferCriteriaResolverOutOfRange();
}
// Retrieve relevant item using order and component index.
OfferItem memory offer = (
orderParameters.offer[componentIndex]
);
// Read item type and criteria from memory & place on stack.
itemType = offer.itemType;
identifierOrCriteria = offer.identifierOrCriteria;
// Optimistically update item type to remove criteria usage.
if (itemType == ItemType.ERC721_WITH_CRITERIA) {
offer.itemType = ItemType.ERC721;
} else {
offer.itemType = ItemType.ERC1155;
}
// Optimistically update identifier w/ supplied identifier.
offer.identifierOrCriteria = criteriaResolver.identifier;
} else {
// Otherwise, the resolver refers to a consideration item.
// Ensure that the component index is in range.
if (componentIndex >= orderParameters.consideration.length) {
revert ConsiderationCriteriaResolverOutOfRange();
}
// Retrieve relevant item using order and component index.
ConsiderationItem memory consideration = (
orderParameters.consideration[componentIndex]
);
// Read item type and criteria from memory & place on stack.
itemType = consideration.itemType;
identifierOrCriteria = consideration.identifierOrCriteria;
// Optimistically update item type to remove criteria usage.
if (itemType == ItemType.ERC721_WITH_CRITERIA) {
consideration.itemType = ItemType.ERC721;
} else {
consideration.itemType = ItemType.ERC1155;
}
// Optimistically update identifier w/ supplied identifier.
consideration.identifierOrCriteria = (
criteriaResolver.identifier
);
}
// Ensure the specified item type indicates criteria usage.
if (!_isItemWithCriteria(itemType)) {
revert CriteriaNotEnabledForItem();
}
// If criteria is not 0 (i.e. a collection-wide offer)...
if (identifierOrCriteria != uint256(0)) {
// Verify identifier inclusion in criteria root using proof.
_verifyProof(
criteriaResolver.identifier,
identifierOrCriteria,
criteriaResolver.criteriaProof
);
} else if (criteriaResolver.criteriaProof.length != 0) {
// Revert if a proof is supplied for a collection-wide item.
revert InvalidProof();
}
}
// Validate Criteria on order has been resolved
// Read consideration length from memory and place on stack.
uint256 totalItems = (advancedOrder.parameters.consideration.length);
// Iterate over each consideration item on the order.
for (uint256 i = 0; i < totalItems; ++i) {
// Ensure item type no longer indicates criteria usage.
if (
_isItemWithCriteria(
advancedOrder.parameters.consideration[i].itemType
)
) {
if (
advancedOrder.parameters.orderType != OrderType.CONTRACT ||
advancedOrder
.parameters
.consideration[i]
.identifierOrCriteria !=
0
) {
revert UnresolvedConsiderationCriteria(0, i);
}
}
}
// Read offer length from memory and place on stack.
totalItems = advancedOrder.parameters.offer.length;
// Iterate over each offer item on the order.
for (uint256 i = 0; i < totalItems; ++i) {
// Ensure item type no longer indicates criteria usage.
if (
_isItemWithCriteria(advancedOrder.parameters.offer[i].itemType)
) {
if (
advancedOrder.parameters.orderType != OrderType.CONTRACT ||
advancedOrder.parameters.offer[i].identifierOrCriteria != 0
) {
revert UnresolvedOfferCriteria(0, i);
}
}
}
}
/**
* @dev Internal pure function to check whether a given item type represents
* a criteria-based ERC721 or ERC1155 item (e.g. an item that can be
* resolved to one of a number of different identifiers at the time of
* order fulfillment).
*
* @param itemType The item type in question.
*
* @return withCriteria A boolean indicating that the item type in question
* represents a criteria-based item.
*/
function _isItemWithCriteria(
ItemType itemType
) internal pure returns (bool withCriteria) {
// ERC721WithCriteria is item type 4. ERC1155WithCriteria is item type
// 5.
withCriteria = uint256(itemType) > 3;
}
/**
* @dev Internal pure function to ensure that a given element is contained
* in a merkle root via a supplied proof.
*
* @param leaf The element for which to prove inclusion.
* @param root The merkle root that inclusion will be proved against.
* @param proof The merkle proof.
*/
function _verifyProof(
uint256 leaf,
uint256 root,
bytes32[] memory proof
) internal pure {
// Hash the supplied leaf to use as the initial proof element.
bytes32 computedHash = keccak256(abi.encodePacked(leaf));
// Iterate over each proof element.
for (uint256 i = 0; i < proof.length; ++i) {
// Retrieve the proof element.
bytes32 proofElement = proof[i];
// Sort and hash proof elements and update the computed hash.
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of proof)
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
// Hash(current element of proof + current computed hash)
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
}
// Ensure that the final derived hash matches the expected root.
if (computedHash != bytes32(root)) {
revert InvalidProof();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
enum ConduitItemType {
NATIVE, // unused
ERC20,
ERC721,
ERC1155
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @title AmountDerivationErrors
* @author 0age
* @notice AmountDerivationErrors contains errors related to amount derivation.
*/
interface AmountDerivationErrors {
/**
* @dev Revert with an error when attempting to apply a fraction as part of
* a partial fill that does not divide the target amount cleanly.
*/
error InexactFraction();
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import { Side } from "../lib/ConsiderationEnums.sol";
/**
* @title CriteriaResolutionErrors
* @author 0age
* @notice CriteriaResolutionErrors contains all errors related to criteria
* resolution.
*/
interface CriteriaResolutionErrors {
/**
* @dev Revert with an error when providing a criteria resolver that refers
* to an order that has not been supplied.
*
* @param side The side of the order that was not supplied.
*/
error OrderCriteriaResolverOutOfRange(Side side);
/**
* @dev Revert with an error if an offer item still has unresolved criteria
* after applying all criteria resolvers.
*
* @param orderIndex The index of the order that contains the offer item.
* @param offerIndex The index of the offer item that still has unresolved
* criteria.
*/
error UnresolvedOfferCriteria(uint256 orderIndex, uint256 offerIndex);
/**
* @dev Revert with an error if a consideration item still has unresolved
* criteria after applying all criteria resolvers.
*
* @param orderIndex The index of the order that contains the
* consideration item.
* @param considerationIndex The index of the consideration item that still
* has unresolved criteria.
*/
error UnresolvedConsiderationCriteria(
uint256 orderIndex,
uint256 considerationIndex
);
/**
* @dev Revert with an error when providing a criteria resolver that refers
* to an order with an offer item that has not been supplied.
*/
error OfferCriteriaResolverOutOfRange();
/**
* @dev Revert with an error when providing a criteria resolver that refers
* to an order with a consideration item that has not been supplied.
*/
error ConsiderationCriteriaResolverOutOfRange();
/**
* @dev Revert with an error when providing a criteria resolver that refers
* to an order with an item that does not expect a criteria to be
* resolved.
*/
error CriteriaNotEnabledForItem();
/**
* @dev Revert with an error when providing a criteria resolver that
* contains an invalid proof with respect to the given item and
* chosen identifier.
*/
error InvalidProof();
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
OrderType,
ItemType
} from "seaport-types/src/lib/ConsiderationEnums.sol";
import {
AdvancedOrder,
ConsiderationItem,
OfferItem,
Order,
OrderComponents,
OrderParameters,
OrderStatus,
ReceivedItem,
SpentItem
} from "seaport-types/src/lib/ConsiderationStructs.sol";
import { ReferenceExecutor } from "./ReferenceExecutor.sol";
import { ReferenceZoneInteraction } from "./ReferenceZoneInteraction.sol";
import {
ContractOffererInterface
} from "seaport-types/src/interfaces/ContractOffererInterface.sol";
import {
ReferenceGenerateOrderReturndataDecoder
} from "./ReferenceGenerateOrderReturndataDecoder.sol";
import {
OrderToExecute,
OrderValidation
} from "./ReferenceConsiderationStructs.sol";
/**
* @title OrderValidator
* @author 0age
* @notice OrderValidator contains functionality related to validating orders
* and updating their status.
*/
contract ReferenceOrderValidator is
ReferenceExecutor,
ReferenceZoneInteraction
{
// Track status of each order (validated, cancelled, and fraction filled).
mapping(bytes32 => OrderStatus) private _orderStatus;
// Track nonces for contract offerers.
mapping(address => uint256) internal _contractNonces;
/**
* @dev Derive and set hashes, reference chainId, and associated domain
* separator during deployment.
*
* @param conduitController A contract that deploys conduits, or proxies
* that may optionally be used to transfer approved
* ERC20/721/1155 tokens.
*/
constructor(
address conduitController
) ReferenceExecutor(conduitController) {}
/**
* @dev Internal function to verify and update the status of a basic order.
*
* @param orderHash The hash of the order.
* @param offerer The offerer of the order.
* @param signature A signature from the offerer indicating that the order
* has been approved.
*/
function _validateBasicOrderAndUpdateStatus(
bytes32 orderHash,
address offerer,
bytes memory signature
) internal {
// Retrieve the order status for the given order hash.
OrderStatus storage orderStatus = _orderStatus[orderHash];
// Ensure order is fillable and is not cancelled.
_verifyOrderStatus(
orderHash,
orderStatus,
true, // Only allow unused orders when fulfilling basic orders.
true // Signifies to revert if the order is invalid.
);
// If the order is not already validated, verify the supplied signature.
if (!orderStatus.isValidated) {
_verifySignature(offerer, orderHash, signature);
}
// Update order status as fully filled, packing struct values.
orderStatus.isValidated = true;
orderStatus.isCancelled = false;
orderStatus.numerator = 1;
orderStatus.denominator = 1;
}
/**
* @dev Internal function to validate an order and determine what portion to
* fill. The desired fill amount is supplied as a fraction, as is the
* returned amount to fill.
*
* @param advancedOrder The order to fulfill as well as the fraction to
* fill. Note that all offer and consideration
* amounts must divide with no remainder in order for
* a partial fill to be valid.
* @param revertOnInvalid A boolean indicating whether to revert if the
* order is invalid due to the time or order status.
*
* @return orderValidation The order validation details, including the fill
* amount.
*/
function _validateOrder(
AdvancedOrder memory advancedOrder,
bool revertOnInvalid
) internal view returns (OrderValidation memory orderValidation) {
// Retrieve the parameters for the order.
OrderParameters memory orderParameters = advancedOrder.parameters;
// Ensure current timestamp falls between order start time and end time.
if (
!_verifyTime(
orderParameters.startTime,
orderParameters.endTime,
revertOnInvalid
)
) {
// Assuming an invalid time and no revert, return zeroed out values.
return
OrderValidation(
bytes32(0),
0,
0,
_convertAdvancedToOrder(orderParameters, 0)
);
}
// Read numerator and denominator from memory and place on the stack.
uint256 numerator = uint256(advancedOrder.numerator);
uint256 denominator = uint256(advancedOrder.denominator);
// If the order is a contract order, return the generated order.
if (orderParameters.orderType == OrderType.CONTRACT) {
// Ensure that numerator and denominator are both equal to 1.
if (numerator != 1 || denominator != 1) {
revert BadFraction();
}
return
OrderValidation(
bytes32(uint256(1)),
1,
1,
_convertAdvancedToOrder(orderParameters, 1)
);
}
// Ensure that the supplied numerator and denominator are valid. The
// numerator should not exceed denominator and should not be zero.
if (numerator > denominator || numerator == 0) {
revert BadFraction();
}
// If attempting partial fill (n < d) check order type & ensure support.
if (
numerator < denominator &&
_doesNotSupportPartialFills(orderParameters.orderType)
) {
// Revert if partial fill was attempted on an unsupported order.
revert PartialFillsNotEnabledForOrder();
}
// Retrieve current counter and use it w/ parameters to get order hash.
orderValidation.orderHash = (
_assertConsiderationLengthAndGetOrderHash(orderParameters)
);
// Retrieve the order status using the derived order hash.
OrderStatus storage orderStatus = (
_orderStatus[orderValidation.orderHash]
);
// Ensure order is fillable and is not cancelled.
if (
// Allow partially used orders to be filled.
!_verifyOrderStatus(
orderValidation.orderHash,
orderStatus,
false,
revertOnInvalid
)
) {
// Assuming an invalid order status and no revert, return zero fill.
return
OrderValidation(
orderValidation.orderHash,
0,
0,
_convertAdvancedToOrder(orderParameters, 0)
);
}
// If the order is not already validated, verify the supplied signature.
if (!orderStatus.isValidated) {
_verifySignature(
orderParameters.offerer,
orderValidation.orderHash,
advancedOrder.signature
);
}
// Read filled amount as numerator and denominator and put on the stack.
uint256 filledNumerator = uint256(orderStatus.numerator);
uint256 filledDenominator = uint256(orderStatus.denominator);
// If order currently has a non-zero denominator it is partially filled.
if (filledDenominator != 0) {
// If denominator of 1 supplied, fill all remaining amount on order.
if (denominator == 1) {
// Scale numerator & denominator to match current denominator.
numerator = filledDenominator;
denominator = filledDenominator;
}
// Otherwise, if supplied denominator differs from current one...
else if (filledDenominator != denominator) {
// scale current numerator by the supplied denominator, then...
filledNumerator *= denominator;
// the supplied numerator & denominator by current denominator.
numerator *= filledDenominator;
denominator *= filledDenominator;
}
// Once adjusted, if current+supplied numerator exceeds denominator:
if (filledNumerator + numerator > denominator) {
// Reduce current numerator so it + supplied = denominator.
numerator = denominator - filledNumerator;
}
// Increment the filled numerator by the new numerator.
filledNumerator += numerator;
// Ensure fractional amounts are below max uint120.
if (
filledNumerator > type(uint120).max ||
denominator > type(uint120).max
) {
// Derive greatest common divisor using euclidean algorithm.
uint256 scaleDown = _greatestCommonDivisor(
numerator,
_greatestCommonDivisor(filledNumerator, denominator)
);
// Scale all fractional values down by gcd.
numerator = numerator / scaleDown;
filledNumerator = filledNumerator / scaleDown;
denominator = denominator / scaleDown;
// Perform the overflow check a second time.
uint256 maxOverhead = type(uint256).max - type(uint120).max;
((filledNumerator + maxOverhead) & (denominator + maxOverhead));
}
}
// Return order hash, new numerator and denominator.
return
OrderValidation(
orderValidation.orderHash,
uint120(numerator),
uint120(denominator),
_convertAdvancedToOrder(orderParameters, uint120(numerator))
);
}
/**
* @dev Internal function to update an order's status.
*
* @param orderHash The hash of the order.
* @param numerator The numerator of the fraction to fill.
* @param denominator The denominator of the fraction to fill.
* @param revertOnInvalid Whether to revert on invalid input.
*
* @return valid A boolean indicating whether the order is valid.
*/
function _updateStatus(
bytes32 orderHash,
uint256 numerator,
uint256 denominator,
bool revertOnInvalid
) internal returns (bool valid) {
if (numerator == 0) {
return false;
}
// Retrieve the order status using the provided order hash.
OrderStatus storage orderStatus = _orderStatus[orderHash];
// Read filled amount as numerator and denominator and put on the stack.
uint256 filledNumerator = uint256(orderStatus.numerator);
uint256 filledDenominator = uint256(orderStatus.denominator);
// If order currently has a non-zero denominator it is partially filled.
if (filledDenominator != 0) {
// if supplied denominator differs from current one...
if (filledDenominator != denominator) {
// scale current numerator by the supplied denominator, then...
filledNumerator *= denominator;
// the supplied numerator & denominator by current denominator.
numerator *= filledDenominator;
denominator *= filledDenominator;
}
// Once adjusted, if current+supplied numerator exceeds
// denominator...
if (filledNumerator + numerator > denominator) {
// Revert or return false, which indicates that the order is
// invalid.
if (revertOnInvalid) {
revert OrderAlreadyFilled(orderHash);
} else {
return false;
}
}
// Increment the filled numerator by the new numerator.
filledNumerator += numerator;
// Ensure fractional amounts are below max uint120.
if (
filledNumerator > type(uint120).max ||
denominator > type(uint120).max
) {
// Derive greatest common divisor using euclidean algorithm.
uint256 scaleDown = _greatestCommonDivisor(
filledNumerator,
denominator
);
// Scale new filled fractional values down by gcd.
filledNumerator = filledNumerator / scaleDown;
denominator = denominator / scaleDown;
// Perform the overflow check a second time.
uint256 maxOverhead = type(uint256).max - type(uint120).max;
((filledNumerator + maxOverhead) & (denominator + maxOverhead));
}
// Update order status and fill amount, packing struct values.
orderStatus.isValidated = true;
orderStatus.isCancelled = false;
orderStatus.numerator = uint120(filledNumerator);
orderStatus.denominator = uint120(denominator);
} else {
// If the order currently has a zero denominator, it is not
// partially filled. Update the order status and fill amount,
// packing struct values.
orderStatus.isValidated = true;
orderStatus.isCancelled = false;
orderStatus.numerator = uint120(numerator);
orderStatus.denominator = uint120(denominator);
}
return true;
}
function _callGenerateOrder(
OrderParameters memory orderParameters,
bytes memory context,
SpentItem[] memory originalOfferItems,
SpentItem[] memory originalConsiderationItems
) internal returns (bool success, bytes memory returnData) {
return
orderParameters.offerer.call(
abi.encodeWithSelector(
ContractOffererInterface.generateOrder.selector,
msg.sender,
originalOfferItems,
originalConsiderationItems,
context
)
);
}
/**
* @dev Internal function to generate a contract order. When a
* collection-wide criteria-based item (criteria = 0) is provided as an
* input to a contract order, the contract offerer has full latitude to
* choose any identifier it wants mid-flight, which differs from the
* usual behavior. For regular criteria-based orders with
* identifierOrCriteria = 0, the fulfiller can pick which identifier to
* receive by providing a CriteriaResolver. For contract offers with
* identifierOrCriteria = 0, Seaport does not expect a corresponding
* CriteriaResolver, and will revert if one is provided.
*
* @param orderToExecute The order to execute.
* @param orderParameters The parameters for the order.
* @param context The context for generating the order.
* @param revertOnInvalid Whether to revert on invalid input.
*
* @return orderHash The order hash.
*/
function _getGeneratedOrder(
OrderToExecute memory orderToExecute,
OrderParameters memory orderParameters,
bytes memory context,
bool revertOnInvalid
) internal returns (bytes32 orderHash) {
// Ensure that consideration array length is equal to the total original
// consideration items value.
if (
orderParameters.consideration.length !=
orderParameters.totalOriginalConsiderationItems
) {
revert ConsiderationLengthNotEqualToTotalOriginal();
}
// Convert offer and consideration to spent and received items.
SpentItem[] memory originalOfferItems = orderToExecute.spentItems;
SpentItem[] memory originalConsiderationItems = _convertToSpent(
orderToExecute.receivedItems
);
// Create arrays for returned offer and consideration items.
SpentItem[] memory offer;
ReceivedItem[] memory consideration;
{
// Do a low-level call to get success status and any return data.
(bool success, bytes memory returnData) = _callGenerateOrder(
orderParameters,
context,
originalOfferItems,
originalConsiderationItems
);
{
// Increment contract nonce and use it to derive order hash.
// Note: nonce will be incremented even for skipped orders, and
// even if generateOrder's return data doesn't meet constraints.
uint256 contractNonce = (
_contractNonces[orderParameters.offerer]++
);
// Derive order hash from contract nonce and offerer address.
orderHash = bytes32(
contractNonce ^
(uint256(uint160(orderParameters.offerer)) << 96)
);
}
// If call succeeds, try to decode offer and consideration items.
if (success) {
// Try to decode offer and consideration items from returndata.
try
(new ReferenceGenerateOrderReturndataDecoder()).decode(
returnData
)
returns (
SpentItem[] memory _offer,
ReceivedItem[] memory _consideration
) {
offer = _offer;
consideration = _consideration;
} catch {
// If decoding fails, revert.
revert InvalidContractOrder(orderHash);
}
} else {
// If the call fails, revert or return empty.
(orderHash, orderToExecute) = _revertOrReturnEmpty(
revertOnInvalid,
orderHash
);
return orderHash;
}
}
{
// Designate lengths.
uint256 originalOfferLength = orderParameters.offer.length;
uint256 newOfferLength = offer.length;
// Explicitly specified offer items cannot be removed.
if (originalOfferLength > newOfferLength) {
revert InvalidContractOrder(orderHash);
}
// Loop through each new offer and ensure the new amounts are at
// least as much as the respective original amounts.
for (uint256 i = 0; i < originalOfferLength; ++i) {
// Designate original and new offer items.
SpentItem memory originalOffer = orderToExecute.spentItems[i];
SpentItem memory newOffer = offer[i];
// Set returned identifier for criteria-based items with
// criteria = 0. Note that this reset means that a contract
// offerer has full latitude to choose any identifier it wants
// mid-flight, in contrast to the normal behavior, where the
// fulfiller can pick which identifier to receive by providing a
// CriteriaResolver.
if (
uint256(originalOffer.itemType) > 3 &&
originalOffer.identifier == 0
) {
originalOffer.itemType = ItemType(
uint256(originalOffer.itemType) - 2
);
originalOffer.identifier = newOffer.identifier;
}
// Ensure the original and generated items are compatible.
if (
originalOffer.amount > newOffer.amount ||
originalOffer.itemType != newOffer.itemType ||
originalOffer.token != newOffer.token ||
originalOffer.identifier != newOffer.identifier
) {
revert InvalidContractOrder(orderHash);
}
}
orderToExecute.spentItems = offer;
orderToExecute.spentItemOriginalAmounts = new uint256[](
offer.length
);
// Add new offer items if there are more than original.
for (uint256 i = 0; i < offer.length; ++i) {
orderToExecute.spentItemOriginalAmounts[i] = offer[i].amount;
}
}
{
// Designate lengths & memory locations.
ReceivedItem[] memory originalConsiderationArray = (
orderToExecute.receivedItems
);
uint256 newConsiderationLength = consideration.length;
// New consideration items cannot be created.
if (newConsiderationLength > originalConsiderationArray.length) {
revert InvalidContractOrder(orderHash);
}
// Loop through and check consideration.
for (uint256 i = 0; i < newConsiderationLength; ++i) {
ReceivedItem memory newConsideration = consideration[i];
ReceivedItem memory originalConsideration = (
originalConsiderationArray[i]
);
if (
uint256(originalConsideration.itemType) > 3 &&
originalConsideration.identifier == 0
) {
originalConsideration.itemType = ItemType(
uint256(originalConsideration.itemType) - 2
);
originalConsideration.identifier = (
newConsideration.identifier
);
}
// All fields must match the originally supplied fields except
// for the amount (which may be reduced by the contract offerer)
// and the recipient if some non-zero address has been provided.
if (
newConsideration.amount > originalConsideration.amount ||
originalConsideration.itemType !=
newConsideration.itemType ||
originalConsideration.token != newConsideration.token ||
originalConsideration.identifier !=
newConsideration.identifier ||
(originalConsideration.recipient != address(0) &&
originalConsideration.recipient !=
(newConsideration.recipient))
) {
revert InvalidContractOrder(orderHash);
}
}
orderToExecute.receivedItems = consideration;
orderToExecute.receivedItemOriginalAmounts = new uint256[](
consideration.length
);
// Iterate over original consideration array and copy to new.
for (uint256 i = 0; i < consideration.length; ++i) {
orderToExecute.receivedItemOriginalAmounts[i] = (
consideration[i].amount
);
}
}
// Return the order hash.
return orderHash;
}
/**
* @dev Internal function to cancel an arbitrary number of orders. Note that
* only the offerer or the zone of a given order may cancel it. Callers
* should ensure that the intended order was cancelled by calling
* `getOrderStatus` and confirming that `isCancelled` returns `true`.
* Also note that contract orders are not cancellable.
*
* @param orders The orders to cancel.
*
* @return A boolean indicating whether the supplied orders were
* successfully cancelled.
*/
function _cancel(
OrderComponents[] calldata orders
) internal returns (bool) {
// Declare variables outside of the loop.
OrderStatus storage orderStatus;
address offerer;
address zone;
// Read length of the orders array from memory and place on stack.
uint256 totalOrders = orders.length;
// Iterate over each order.
for (uint256 i = 0; i < totalOrders; ++i) {
// Retrieve the order.
OrderComponents calldata order = orders[i];
offerer = order.offerer;
zone = order.zone;
// Ensure caller is either offerer or zone of the order and that the
// order is not a contract order.
if (
order.orderType == OrderType.CONTRACT ||
(msg.sender != offerer && msg.sender != zone)
) {
revert CannotCancelOrder();
}
// Derive order hash using the order parameters and the counter.
bytes32 orderHash = _deriveOrderHash(
OrderParameters(
offerer,
zone,
order.offer,
order.consideration,
order.orderType,
order.startTime,
order.endTime,
order.zoneHash,
order.salt,
order.conduitKey,
order.consideration.length
),
order.counter
);
// Retrieve the order status using the derived order hash.
orderStatus = _orderStatus[orderHash];
// Update the order status as not valid and cancelled.
orderStatus.isValidated = false;
orderStatus.isCancelled = true;
// Emit an event signifying that the order has been cancelled.
emit OrderCancelled(orderHash, offerer, zone);
}
return true;
}
/**
* @dev Internal function to validate an arbitrary number of orders, thereby
* registering them as valid and allowing the fulfiller to skip
* verification. Note that anyone can validate a signed order but only
* the offerer can validate an order without supplying a signature.
*
* @param orders The orders to validate.
*
* @return A boolean indicating whether the supplied orders were
* successfully validated.
*/
function _validate(Order[] calldata orders) internal returns (bool) {
// Declare variables outside of the loop.
OrderStatus storage orderStatus;
bytes32 orderHash;
address offerer;
// Read length of the orders array from memory and place on stack.
uint256 totalOrders = orders.length;
// Iterate over each order.
for (uint256 i = 0; i < totalOrders; ++i) {
// Retrieve the order.
Order calldata order = orders[i];
// Retrieve the order parameters.
OrderParameters calldata orderParameters = order.parameters;
// Skip contract orders.
if (orderParameters.orderType == OrderType.CONTRACT) {
continue;
}
// Move offerer from memory to the stack.
offerer = orderParameters.offerer;
// Get current counter and use it w/ params to derive order hash.
orderHash = _assertConsiderationLengthAndGetOrderHash(
orderParameters
);
// Retrieve the order status using the derived order hash.
orderStatus = _orderStatus[orderHash];
// Ensure order is fillable and retrieve the filled amount.
_verifyOrderStatus(
orderHash,
orderStatus,
false, // Signifies that partially filled orders are valid.
true // Signifies to revert if the order is invalid.
);
// If the order has not already been validated...
if (!orderStatus.isValidated) {
// Ensure that consideration array length is equal to the total
// original consideration items value.
if (
orderParameters.consideration.length !=
orderParameters.totalOriginalConsiderationItems
) {
revert ConsiderationLengthNotEqualToTotalOriginal();
}
// Verify the supplied signature.
_verifySignature(offerer, orderHash, order.signature);
// Update order status to mark the order as valid.
orderStatus.isValidated = true;
// Emit an event signifying the order has been validated.
emit OrderValidated(orderHash, orderParameters);
}
}
return true;
}
/**
* @dev Internal view function to retrieve the status of a given order by
* hash, including whether the order has been cancelled or validated
* and the fraction of the order that has been filled.
*
* @param orderHash The order hash in question.
*
* @return isValidated A boolean indicating whether the order in question
* has been validated (i.e. previously approved or
* partially filled).
* @return isCancelled A boolean indicating whether the order in question
* has been cancelled.
* @return totalFilled The total portion of the order that has been filled
* (i.e. the "numerator").
* @return totalSize The total size of the order that is either filled or
* unfilled (i.e. the "denominator").
*/
function _getOrderStatus(
bytes32 orderHash
)
internal
view
returns (
bool isValidated,
bool isCancelled,
uint256 totalFilled,
uint256 totalSize
)
{
// Retrieve the order status using the order hash.
OrderStatus storage orderStatus = _orderStatus[orderHash];
// Return the fields on the order status.
return (
orderStatus.isValidated,
orderStatus.isCancelled,
orderStatus.numerator,
orderStatus.denominator
);
}
/**
* @dev Internal pure function to either revert or return an empty tuple
* depending on the value of `revertOnInvalid`.
*
* @param revertOnInvalid Whether to revert on invalid input.
* @param contractOrderHash The contract order hash.
*
* @return orderHash The order hash.
*/
function _revertOrReturnEmpty(
bool revertOnInvalid,
bytes32 contractOrderHash
)
internal
pure
returns (bytes32 orderHash, OrderToExecute memory emptyOrder)
{
// If invalid input should not revert...
if (!revertOnInvalid) {
// Return no contract order hash and zero values for the numerator
// and denominator.
return (bytes32(0), emptyOrder);
}
// Otherwise, revert.
revert InvalidContractOrder(contractOrderHash);
}
/**
* @dev Internal pure function to convert received items to spent items.
*
* @param consideration The consideration items to convert.
*
* @return receivedItems The converted received items.
*/
function _convertToSpent(
ReceivedItem[] memory consideration
) internal pure returns (SpentItem[] memory receivedItems) {
// Create an array of received items equal to the consideration length.
receivedItems = new SpentItem[](consideration.length);
// Iterate over each received item on the order.
for (uint256 i = 0; i < consideration.length; ++i) {
// Retrieve the consideration item.
ReceivedItem memory considerationItem = (consideration[i]);
// Create spent item for event based on the consideration item.
SpentItem memory receivedItem = SpentItem(
considerationItem.itemType,
considerationItem.token,
considerationItem.identifier,
considerationItem.amount
);
// Add to array of received items.
receivedItems[i] = receivedItem;
}
}
/**
* @dev Internal function to derive the greatest common divisor of two
* values using the classical euclidian algorithm.
*
* @param a The first value.
* @param b The second value.
*
* @return greatestCommonDivisor The greatest common divisor.
*/
function _greatestCommonDivisor(
uint256 a,
uint256 b
) internal pure returns (uint256 greatestCommonDivisor) {
while (b > 0) {
uint256 c = b;
b = a % c;
a = c;
}
greatestCommonDivisor = a;
}
/**
* @dev Internal pure function to check whether a given order type indicates
* that partial fills are not supported (e.g. only "full fills" are
* allowed for the order in question).
*
* @param orderType The order type in question.
*
* @return isFullOrder A boolean indicating whether the order type only
* supports full fills.
*/
function _doesNotSupportPartialFills(
OrderType orderType
) internal pure returns (bool isFullOrder) {
// The "full" order types are even, while "partial" order types are odd.
isFullOrder = uint256(orderType) & 1 == 0;
}
/**
* @dev Internal pure function to convert an advanced order to an order
* to execute.
*
* @param orderParameters The order to convert.
*
* @return orderToExecute The new order to execute.
*/
function _convertAdvancedToOrder(
OrderParameters memory orderParameters,
uint120 numerator
) internal pure returns (OrderToExecute memory orderToExecute) {
// Retrieve the advanced orders offers.
OfferItem[] memory offer = orderParameters.offer;
// Create an array of spent items equal to the offer length.
SpentItem[] memory spentItems = new SpentItem[](offer.length);
uint256[] memory spentItemOriginalAmounts = new uint256[](offer.length);
// Iterate over each offer item on the order.
for (uint256 i = 0; i < offer.length; ++i) {
// Retrieve the offer item.
OfferItem memory offerItem = offer[i];
// Create spent item for event based on the offer item.
SpentItem memory spentItem = SpentItem(
offerItem.itemType,
offerItem.token,
offerItem.identifierOrCriteria,
offerItem.startAmount
);
// Add to array of spent items.
spentItems[i] = spentItem;
spentItemOriginalAmounts[i] = offerItem.startAmount;
}
// Retrieve the consideration array from the advanced order.
ConsiderationItem[] memory consideration = orderParameters
.consideration;
// Create an array of received items equal to the consideration length.
ReceivedItem[] memory receivedItems = new ReceivedItem[](
consideration.length
);
// Create an array of uint256 values equal in length to the
// consideration length containing the amounts of each item.
uint256[] memory receivedItemOriginalAmounts = new uint256[](
consideration.length
);
// Iterate over each consideration item on the order.
for (uint256 i = 0; i < consideration.length; ++i) {
// Retrieve the consideration item.
ConsiderationItem memory considerationItem = (consideration[i]);
// Create received item for event based on the consideration item.
ReceivedItem memory receivedItem = ReceivedItem(
considerationItem.itemType,
considerationItem.token,
considerationItem.identifierOrCriteria,
considerationItem.startAmount,
considerationItem.recipient
);
// Add to array of received items.
receivedItems[i] = receivedItem;
// Add to array of received item amounts.
receivedItemOriginalAmounts[i] = considerationItem.startAmount;
}
// Create the order to execute from the advanced order data.
orderToExecute = OrderToExecute(
orderParameters.offerer,
spentItems,
receivedItems,
orderParameters.conduitKey,
numerator,
spentItemOriginalAmounts,
receivedItemOriginalAmounts
);
// Return the order.
return orderToExecute;
}
/**
* @dev Internal pure function to convert an array of advanced orders to
* an array of orders to execute.
*
* @param advancedOrders The advanced orders to convert.
*
* @return ordersToExecute The new array of orders.
*/
function _convertAdvancedToOrdersToExecute(
AdvancedOrder[] memory advancedOrders
) internal pure returns (OrderToExecute[] memory ordersToExecute) {
// Read the number of orders from memory and place on the stack.
uint256 totalOrders = advancedOrders.length;
// Allocate new empty array for each advanced order in memory.
ordersToExecute = new OrderToExecute[](totalOrders);
// Iterate over the given orders.
for (uint256 i = 0; i < totalOrders; ++i) {
// Convert and update array.
ordersToExecute[i] = _convertAdvancedToOrder(
advancedOrders[i].parameters,
advancedOrders[i].numerator
);
}
// Return the array of orders to execute
return ordersToExecute;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ReceivedItem,
Schema,
SpentItem
} from "../lib/ConsiderationStructs.sol";
import { IERC165 } from "../interfaces/IERC165.sol";
/**
* @title ContractOffererInterface
* @notice Contains the minimum interfaces needed to interact with a contract
* offerer.
*/
interface ContractOffererInterface is IERC165 {
/**
* @dev Generates an order with the specified minimum and maximum spent
* items, and optional context (supplied as extraData).
*
* @param fulfiller The address of the fulfiller.
* @param minimumReceived The minimum items that the caller is willing to
* receive.
* @param maximumSpent The maximum items the caller is willing to spend.
* @param context Additional context of the order.
*
* @return offer A tuple containing the offer items.
* @return consideration A tuple containing the consideration items.
*/
function generateOrder(
address fulfiller,
SpentItem[] calldata minimumReceived,
SpentItem[] calldata maximumSpent,
bytes calldata context // encoded based on the schemaID
)
external
returns (SpentItem[] memory offer, ReceivedItem[] memory consideration);
/**
* @dev Ratifies an order with the specified offer, consideration, and
* optional context (supplied as extraData).
*
* @param offer The offer items.
* @param consideration The consideration items.
* @param context Additional context of the order.
* @param orderHashes The hashes to ratify.
* @param contractNonce The nonce of the contract.
*
* @return ratifyOrderMagicValue The magic value returned by the contract
* offerer.
*/
function ratifyOrder(
SpentItem[] calldata offer,
ReceivedItem[] calldata consideration,
bytes calldata context, // encoded based on the schemaID
bytes32[] calldata orderHashes,
uint256 contractNonce
) external returns (bytes4 ratifyOrderMagicValue);
/**
* @dev View function to preview an order generated in response to a minimum
* set of received items, maximum set of spent items, and context
* (supplied as extraData).
*
* @param caller The address of the caller (e.g. Seaport).
* @param fulfiller The address of the fulfiller (e.g. the account
* calling Seaport).
* @param minimumReceived The minimum items that the caller is willing to
* receive.
* @param maximumSpent The maximum items the caller is willing to spend.
* @param context Additional context of the order.
*
* @return offer A tuple containing the offer items.
* @return consideration A tuple containing the consideration items.
*/
function previewOrder(
address caller,
address fulfiller,
SpentItem[] calldata minimumReceived,
SpentItem[] calldata maximumSpent,
bytes calldata context // encoded based on the schemaID
)
external
view
returns (SpentItem[] memory offer, ReceivedItem[] memory consideration);
/**
* @dev Gets the metadata for this contract offerer.
*
* @return name The name of the contract offerer.
* @return schemas The schemas supported by the contract offerer.
*/
function getSeaportMetadata()
external
view
returns (string memory name, Schema[] memory schemas); // map to SIP IDs
function supportsInterface(
bytes4 interfaceId
) external view override returns (bool);
// Additional functions and/or events based on implemented schemaIDs
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ConduitItemType
} from "seaport-types/src/conduit/lib/ConduitEnums.sol";
import {
ConduitInterface
} from "seaport-types/src/interfaces/ConduitInterface.sol";
import {
ConduitTransfer
} from "seaport-types/src/conduit/lib/ConduitStructs.sol";
import { ItemType } from "seaport-types/src/lib/ConsiderationEnums.sol";
import { ReceivedItem } from "seaport-types/src/lib/ConsiderationStructs.sol";
import { ReferenceVerifiers } from "./ReferenceVerifiers.sol";
import { ReferenceTokenTransferrer } from "./ReferenceTokenTransferrer.sol";
import { AccumulatorStruct } from "./ReferenceConsiderationStructs.sol";
/**
* @title Executor
* @author 0age
* @notice Executor contains functions related to processing executions (i.e.
* transferring items, either directly or via conduits).
*/
contract ReferenceExecutor is ReferenceVerifiers, ReferenceTokenTransferrer {
/**
* @dev Derive and set hashes, reference chainId, and associated domain
* separator during deployment.
*
* @param conduitController A contract that deploys conduits, or proxies
* that may optionally be used to transfer approved
* ERC20/721/1155 tokens.
*/
constructor(
address conduitController
) ReferenceVerifiers(conduitController) {}
/**
* @dev Internal function to transfer a given item.
*
* @param item The item to transfer including an amount
* and recipient.
* @param offerer The account offering the item, i.e. the
* from address.
* @param conduitKey A bytes32 value indicating what
* corresponding conduit, if any, to source
* token approvals from. The zero hash
* signifies that no conduit should be used
* (and direct approvals set on Consideration)
* @param accumulatorStruct A struct containing conduit transfer data
* and its corresponding conduitKey.
*/
function _transfer(
ReceivedItem memory item,
address offerer,
bytes32 conduitKey,
AccumulatorStruct memory accumulatorStruct
) internal {
// If the item type indicates Ether or a native token...
if (item.itemType == ItemType.NATIVE) {
// Ensure neither the token nor the identifier parameters are set.
if ((uint160(item.token) | item.identifier) != 0) {
revert UnusedItemParameters();
}
// Transfer the native tokens to the recipient.
_transferNativeTokens(item.recipient, item.amount);
} else if (item.itemType == ItemType.ERC20) {
// Ensure that no identifier is supplied.
if (item.identifier != 0) {
revert UnusedItemParameters();
}
// Transfer ERC20 tokens from the offerer to the recipient.
_transferERC20(
item.token,
offerer,
item.recipient,
item.amount,
conduitKey,
accumulatorStruct
);
} else if (item.itemType == ItemType.ERC721) {
// Transfer ERC721 token from the offerer to the recipient.
_transferERC721(
item.token,
offerer,
item.recipient,
item.identifier,
item.amount,
conduitKey,
accumulatorStruct
);
} else {
// Transfer ERC1155 token from the offerer to the recipient.
_transferERC1155(
item.token,
offerer,
item.recipient,
item.identifier,
item.amount,
conduitKey,
accumulatorStruct
);
}
}
/**
* @dev Internal function to transfer Ether or other native tokens to a
* given recipient. Note that this reference implementation deviates
* from the primary contract, which "bubbles up" revert data when
* present (the reference contract always throws a generic error).
*
* @param to The recipient of the transfer.
* @param amount The amount to transfer.
*/
function _transferNativeTokens(
address payable to,
uint256 amount
) internal {
// Ensure that the supplied amount is non-zero.
_assertNonZeroAmount(amount);
// Declare a variable indicating whether the call was successful or not.
(bool success, ) = to.call{ value: amount }("");
// If the call fails...
if (!success) {
// Revert with a generic error message.
revert NativeTokenTransferGenericFailure(to, amount);
}
}
/**
* @dev Internal function to transfer ERC20 tokens from a given originator
* to a given recipient using a given conduit if applicable. Sufficient
* approvals must be set on this contract, the conduit.
*
* @param token The ERC20 token to transfer.
* @param from The originator of the transfer.
* @param to The recipient of the transfer.
* @param amount The amount to transfer.
* @param conduitKey A bytes32 value indicating what
* corresponding conduit, if any, to source
* token approvals from. The zero hash
* signifies that no conduit should be used
* (and direct approvals set on Consideration)
* @param accumulatorStruct A struct containing conduit transfer data
* and its corresponding conduitKey.
*/
function _transferERC20(
address token,
address from,
address to,
uint256 amount,
bytes32 conduitKey,
AccumulatorStruct memory accumulatorStruct
) internal {
// Ensure that the supplied amount is non-zero.
_assertNonZeroAmount(amount);
// Trigger accumulated transfers if the conduits differ.
_triggerIfArmedAndNotAccumulatable(accumulatorStruct, conduitKey);
// If no conduit has been specified...
if (conduitKey == bytes32(0)) {
// Perform the token transfer directly.
_performERC20Transfer(token, from, to, amount);
} else {
// Insert the call to the conduit into the accumulator.
_insert(
conduitKey,
accumulatorStruct,
ConduitItemType.ERC20,
token,
from,
to,
uint256(0),
amount
);
}
}
/**
* @dev Internal function to transfer a single ERC721 token from a given
* originator to a given recipient. Sufficient approvals must be set,
* either on the respective conduit or on this contract itself.
*
* @param token The ERC721 token to transfer.
* @param from The originator of the transfer.
* @param to The recipient of the transfer.
* @param identifier The tokenId to transfer.
* @param amount The "amount" (this value must be equal
* to one).
* @param conduitKey A bytes32 value indicating what
* corresponding conduit, if any, to source
* token approvals from. The zero hash
* signifies that no conduit should be used
* (and direct approvals set on Consideration)
* @param accumulatorStruct A struct containing conduit transfer data
* and its corresponding conduitKey.
*/
function _transferERC721(
address token,
address from,
address to,
uint256 identifier,
uint256 amount,
bytes32 conduitKey,
AccumulatorStruct memory accumulatorStruct
) internal {
// Trigger accumulated transfers if the conduits differ.
_triggerIfArmedAndNotAccumulatable(accumulatorStruct, conduitKey);
// If no conduit has been specified...
if (conduitKey == bytes32(0)) {
// Ensure that exactly one 721 item is being transferred.
if (amount != 1) {
revert InvalidERC721TransferAmount(amount);
}
// Perform transfer via the token contract directly.
_performERC721Transfer(token, from, to, identifier);
} else {
// Insert the call to the conduit into the accumulator.
_insert(
conduitKey,
accumulatorStruct,
ConduitItemType.ERC721,
token,
from,
to,
identifier,
amount
);
}
}
/**
* @dev Internal function to transfer ERC1155 tokens from a given originator
* to a given recipient. Sufficient approvals must be set, either on
* the respective conduit or on this contract itself.
*
* @param token The ERC1155 token to transfer.
* @param from The originator of the transfer.
* @param to The recipient of the transfer.
* @param identifier The tokenId to transfer.
* @param amount The amount to transfer.
* @param conduitKey A bytes32 value indicating what
* corresponding conduit, if any, to source
* token approvals from. The zero hash
* signifies that no conduit should be used
* (and direct approvals set on Consideration)
* @param accumulatorStruct A struct containing conduit transfer data
* and its corresponding conduitKey.
*/
function _transferERC1155(
address token,
address from,
address to,
uint256 identifier,
uint256 amount,
bytes32 conduitKey,
AccumulatorStruct memory accumulatorStruct
) internal {
// Ensure that the supplied amount is non-zero.
_assertNonZeroAmount(amount);
// Trigger accumulated transfers if the conduits differ.
_triggerIfArmedAndNotAccumulatable(accumulatorStruct, conduitKey);
// If no conduit has been specified...
if (conduitKey == bytes32(0)) {
// Perform transfer via the token contract directly.
_performERC1155Transfer(token, from, to, identifier, amount);
} else {
// Insert the call to the conduit into the accumulator.
_insert(
conduitKey,
accumulatorStruct,
ConduitItemType.ERC1155,
token,
from,
to,
identifier,
amount
);
}
}
/**
* @dev Internal function to trigger a call to the conduit currently held by
* the accumulator if the accumulator contains item transfers (i.e. it
* is "armed") and the supplied conduit key does not match the key held
* by the accumulator.
*
* @param accumulatorStruct A struct containing conduit transfer data
* and its corresponding conduitKey.
* @param conduitKey A bytes32 value indicating what corresponding
* conduit, if any, to source token approvals
* from. The zero hash signifies that no conduit
* should be used (and direct approvals set on
* Consideration)
*/
function _triggerIfArmedAndNotAccumulatable(
AccumulatorStruct memory accumulatorStruct,
bytes32 conduitKey
) internal {
// Perform conduit call if the set key does not match the supplied key.
if (accumulatorStruct.conduitKey != conduitKey) {
_triggerIfArmed(accumulatorStruct);
}
}
/**
* @dev Internal function to trigger a call to the conduit currently held by
* the accumulator if the accumulator contains item transfers (i.e. it
* is "armed").
*
* @param accumulatorStruct A struct containing conduit transfer data
* and its corresponding conduitKey.
*/
function _triggerIfArmed(
AccumulatorStruct memory accumulatorStruct
) internal {
// Exit if the accumulator is not "armed".
if (accumulatorStruct.transfers.length == 0) {
return;
}
// Perform conduit call.
_trigger(accumulatorStruct);
}
/**
* @dev Internal function to trigger a call to the conduit corresponding to
* a given conduit key, supplying all accumulated item transfers. The
* accumulator will be "disarmed" and reset in the process.
*
* @param accumulatorStruct A struct containing conduit transfer data
* and its corresponding conduitKey.
*/
function _trigger(AccumulatorStruct memory accumulatorStruct) internal {
// Call the conduit with all the accumulated transfers.
ConduitInterface(_getConduit(accumulatorStruct.conduitKey)).execute(
accumulatorStruct.transfers
);
// Reset accumulator length to signal that it is now "disarmed".
delete accumulatorStruct.transfers;
}
/**
* @dev Internal pure function to place an item transfer into an accumulator
* that collects a series of transfers to execute against a given
* conduit in a single call.
*
* @param conduitKey A bytes32 value indicating what
* corresponding conduit, if any, to source
* token approvals from. The zero hash
* signifies that no conduit should be used
* (and direct approvals set on Consideration)
* @param accumulatorStruct A struct containing conduit transfer data
* and its corresponding conduitKey.
* @param itemType The type of the item to transfer.
* @param token The token to transfer.
* @param from The originator of the transfer.
* @param to The recipient of the transfer.
* @param identifier The tokenId to transfer.
* @param amount The amount to transfer.
*/
function _insert(
bytes32 conduitKey,
AccumulatorStruct memory accumulatorStruct,
ConduitItemType itemType,
address token,
address from,
address to,
uint256 identifier,
uint256 amount
) internal pure {
/**
* The following is highly inefficient, but written this way to
* simply demonstrate what is performed by the optimized contract.
*/
// Get the current length of the accumulator's transfers.
uint256 currentTransferLength = accumulatorStruct.transfers.length;
// Create a new array to "insert" the new transfer.
ConduitTransfer[] memory newTransfers = (
new ConduitTransfer[](currentTransferLength + 1)
);
// Fill new array with old transfers.
for (uint256 i = 0; i < currentTransferLength; ++i) {
// Get the old transfer.
ConduitTransfer memory oldTransfer = accumulatorStruct.transfers[i];
// Add the old transfer into the new array.
newTransfers[i] = ConduitTransfer(
oldTransfer.itemType,
oldTransfer.token,
oldTransfer.from,
oldTransfer.to,
oldTransfer.identifier,
oldTransfer.amount
);
}
// Insert new transfer into array.
newTransfers[currentTransferLength] = ConduitTransfer(
itemType,
token,
from,
to,
identifier,
amount
);
// Set accumulator struct transfers to new transfers.
accumulatorStruct.transfers = newTransfers;
// Set the conduitkey of the current transfers.
accumulatorStruct.conduitKey = conduitKey;
}
/**
* @dev Internal function get the conduit derived by the provided
* conduit key.
*
* @param conduitKey A bytes32 value indicating what corresponding conduit,
* if any, to source token approvals from. This value is
* the "salt" parameter supplied by the deployer (i.e. the
* conduit controller) when deploying the given conduit.
*
* @return conduit The address of the conduit associated with the given
* conduit key.
*/
function _getConduit(
bytes32 conduitKey
) internal view returns (address conduit) {
// Derive the address of the conduit using the conduit key.
conduit = _deriveConduit(conduitKey);
// If the conduit does not have runtime code (i.e. is not deployed)...
if (conduit.code.length == 0) {
// Revert with an error indicating an invalid conduit.
revert InvalidConduit(conduitKey, conduit);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import { ZoneInterface } from "seaport-types/src/interfaces/ZoneInterface.sol";
import {
ContractOffererInterface
} from "seaport-types/src/interfaces/ContractOffererInterface.sol";
import {
ItemType,
OrderType
} from "seaport-types/src/lib/ConsiderationEnums.sol";
import {
AdditionalRecipient,
AdvancedOrder,
BasicOrderParameters,
ReceivedItem,
SpentItem,
ZoneParameters
} from "seaport-types/src/lib/ConsiderationStructs.sol";
import { OrderToExecute } from "./ReferenceConsiderationStructs.sol";
import {
ZoneInteractionErrors
} from "seaport-types/src/interfaces/ZoneInteractionErrors.sol";
/**
* @title ZoneInteraction
* @author 0age
* @notice ZoneInteraction contains logic related to interacting with zones.
*/
contract ReferenceZoneInteraction is ZoneInteractionErrors {
function _assertRestrictedBasicOrderAuthorization(
bytes32 orderHash,
OrderType orderType,
BasicOrderParameters calldata basicOrderParameters,
ItemType offeredItemType,
ItemType receivedItemType
) internal {
// Create a new array for the hash.
bytes32[] memory orderHashes = new bytes32[](0);
// Convert the order params and types to spent and received items.
(
SpentItem[] memory offer,
ReceivedItem[] memory consideration
) = _convertToSpentAndReceivedItems(
basicOrderParameters,
offeredItemType,
receivedItemType
);
// Order types 2-3 require zone or offerer be caller or zone to approve.
// Note that in cases where fulfiller == zone, the restricted order
// validation will be skipped.
if (
(orderType == OrderType.FULL_RESTRICTED ||
orderType == OrderType.PARTIAL_RESTRICTED) &&
msg.sender != basicOrderParameters.zone
) {
// Validate the order with the zone.
if (
ZoneInterface(basicOrderParameters.zone).authorizeOrder(
ZoneParameters({
orderHash: orderHash,
fulfiller: msg.sender,
offerer: basicOrderParameters.offerer,
offer: offer,
consideration: consideration,
extraData: "",
orderHashes: orderHashes,
startTime: basicOrderParameters.startTime,
endTime: basicOrderParameters.endTime,
zoneHash: basicOrderParameters.zoneHash
})
) != ZoneInterface.authorizeOrder.selector
) {
revert InvalidRestrictedOrder(orderHash);
}
}
}
/**
* @dev Internal view function to determine if an order has a restricted
* order type and, if so, to ensure that either the offerer or the zone
* are the fulfiller or that a staticcall to `isValidOrder` on the zone
* returns a magic value indicating that the order is currently valid.
*
* @param orderHash The hash of the order.
* @param basicOrderParameters The original basic order parameters.
* @param offeredItemType The type of the order.
* @param receivedItemType The offerer in question.
*/
function _assertRestrictedBasicOrderValidity(
bytes32 orderHash,
OrderType orderType,
BasicOrderParameters calldata basicOrderParameters,
ItemType offeredItemType,
ItemType receivedItemType
) internal {
// Create a new array for the hash.
bytes32[] memory orderHashes = new bytes32[](1);
orderHashes[0] = orderHash;
// Convert the order params and types to spent and received items.
(
SpentItem[] memory offer,
ReceivedItem[] memory consideration
) = _convertToSpentAndReceivedItems(
basicOrderParameters,
offeredItemType,
receivedItemType
);
// Order types 2-3 require zone or offerer be caller or zone to approve.
// Note that in cases where fulfiller == zone, the restricted order
// validation will be skipped.
if (
(orderType == OrderType.FULL_RESTRICTED ||
orderType == OrderType.PARTIAL_RESTRICTED) &&
msg.sender != basicOrderParameters.zone
) {
// Validate the order with the zone.
if (
ZoneInterface(basicOrderParameters.zone).validateOrder(
ZoneParameters({
orderHash: orderHash,
fulfiller: msg.sender,
offerer: basicOrderParameters.offerer,
offer: offer,
consideration: consideration,
extraData: "",
orderHashes: orderHashes,
startTime: basicOrderParameters.startTime,
endTime: basicOrderParameters.endTime,
zoneHash: basicOrderParameters.zoneHash
})
) != ZoneInterface.validateOrder.selector
) {
revert InvalidRestrictedOrder(orderHash);
}
}
}
/**
* @dev Internal function to check if a restricted advanced order is
* authorized by its zone or offerer, in cases where the caller is not
* the zone or offerer.
*
* @param advancedOrder The advanced order in question.
* @param orderToExecute The order to execute.
* @param orderHashes The order hashes of each order supplied
* alongside the current order as part of a
"match" or "fulfill available" variety of
order fulfillment.
* @param orderHash The hash of the order to execute.
* @param revertOnUnauthorized A boolean indicating whether the function
* should revert if the order is invalid.
*
* @return authorized A boolean indicating whether the order is
* authorized by the zone or offerer.
* @return checked A boolean indicating whether the order has
* been checked for authorization.
*/
function _checkRestrictedAdvancedOrderAuthorization(
AdvancedOrder memory advancedOrder,
OrderToExecute memory orderToExecute,
bytes32[] memory orderHashes,
bytes32 orderHash,
bool revertOnUnauthorized
) internal returns (bool authorized, bool checked) {
// Order types 2-3 require zone or offerer be caller or zone to approve.
if (
(advancedOrder.parameters.orderType == OrderType.FULL_RESTRICTED ||
advancedOrder.parameters.orderType ==
OrderType.PARTIAL_RESTRICTED) &&
msg.sender != advancedOrder.parameters.zone
) {
// Authorize the order.
try
ZoneInterface(advancedOrder.parameters.zone).authorizeOrder(
ZoneParameters({
orderHash: orderHash,
fulfiller: msg.sender,
offerer: advancedOrder.parameters.offerer,
offer: orderToExecute.spentItems,
consideration: orderToExecute.receivedItems,
extraData: advancedOrder.extraData,
orderHashes: orderHashes,
startTime: advancedOrder.parameters.startTime,
endTime: advancedOrder.parameters.endTime,
zoneHash: advancedOrder.parameters.zoneHash
})
)
returns (bytes4 selector) {
if (selector != ZoneInterface.authorizeOrder.selector) {
revert InvalidRestrictedOrder(orderHash);
}
return (true, true);
} catch {
if (revertOnUnauthorized) {
revert InvalidRestrictedOrder(orderHash);
}
return (false, false);
}
} else {
return (true, false);
}
}
/**
* @dev Internal function to validate that a restricted advanced order is
* authorized by its zone or offerer, in cases where the caller is not
* the zone or offerer.
*
* @param advancedOrder The advanced order in question.
* @param orderToExecute The order to execute.
* @param orderHashes The order hashes of each order supplied
* alongside the current order as part of a
"match" or "fulfill available" variety of
order fulfillment.
* @param orderHash The hash of the order to execute.
* @param zoneHash The hash to provide upon calling the zone.
* @param orderType The type of the order.
* @param offerer The offerer in question.
* @param zone The zone in question.
*/
function _assertRestrictedAdvancedOrderAuthorization(
AdvancedOrder memory advancedOrder,
OrderToExecute memory orderToExecute,
bytes32[] memory orderHashes,
bytes32 orderHash,
bytes32 zoneHash,
OrderType orderType,
address offerer,
address zone
) internal {
// Order types 2-3 require zone or offerer be caller or zone to approve.
if (
(orderType == OrderType.FULL_RESTRICTED ||
orderType == OrderType.PARTIAL_RESTRICTED) && msg.sender != zone
) {
// Authorize the order.
if (
ZoneInterface(zone).authorizeOrder(
ZoneParameters({
orderHash: orderHash,
fulfiller: msg.sender,
offerer: offerer,
offer: orderToExecute.spentItems,
consideration: orderToExecute.receivedItems,
extraData: advancedOrder.extraData,
orderHashes: orderHashes,
startTime: advancedOrder.parameters.startTime,
endTime: advancedOrder.parameters.endTime,
zoneHash: zoneHash
})
) != ZoneInterface.authorizeOrder.selector
) {
revert InvalidRestrictedOrder(orderHash);
}
}
}
/**
* @dev Internal view function to determine if a proxy should be utilized
* for a given order and to ensure that the submitter is allowed by the
* order type.
*
* @param advancedOrder The order in question.
* @param orderHashes The order hashes of each order supplied alongside
* the current order as part of a "match" or "fulfill
* available" variety of order fulfillment.
* @param orderHash The hash of the order.
* @param zoneHash The hash to provide upon calling the zone.
* @param orderType The type of the order.
* @param offerer The offerer in question.
* @param zone The zone in question.
*/
function _assertRestrictedAdvancedOrderValidity(
AdvancedOrder memory advancedOrder,
OrderToExecute memory orderToExecute,
bytes32[] memory orderHashes,
bytes32 orderHash,
bytes32 zoneHash,
OrderType orderType,
address offerer,
address zone
) internal {
// Order types 2-3 require zone or offerer be caller or zone to approve.
if (
(orderType == OrderType.FULL_RESTRICTED ||
orderType == OrderType.PARTIAL_RESTRICTED) && msg.sender != zone
) {
// Validate the order.
if (
ZoneInterface(zone).validateOrder(
ZoneParameters({
orderHash: orderHash,
fulfiller: msg.sender,
offerer: offerer,
offer: orderToExecute.spentItems,
consideration: orderToExecute.receivedItems,
extraData: advancedOrder.extraData,
orderHashes: orderHashes,
startTime: advancedOrder.parameters.startTime,
endTime: advancedOrder.parameters.endTime,
zoneHash: zoneHash
})
) != ZoneInterface.validateOrder.selector
) {
revert InvalidRestrictedOrder(orderHash);
}
} else if (orderType == OrderType.CONTRACT) {
// Ratify the contract order.
if (
ContractOffererInterface(offerer).ratifyOrder(
orderToExecute.spentItems,
orderToExecute.receivedItems,
advancedOrder.extraData,
orderHashes,
uint256(orderHash) ^ (uint256(uint160(offerer)) << 96)
) != ContractOffererInterface.ratifyOrder.selector
) {
revert InvalidContractOrder(orderHash);
}
}
}
/**
* @dev Converts the offer and consideration parameters from a
* BasicOrderParameters object into an array of SpentItem and
* ReceivedItem objects.
*
* @param parameters The BasicOrderParameters object containing
* the offer and consideration parameters to be
* converted.
* @param offerItemType The item type of the offer.
* @param considerationItemType The item type of the consideration.
*
* @return spentItems The converted offer parameters as an array
* of SpentItem objects.
* @return receivedItems The converted consideration parameters as an
* array of ReceivedItem objects.
*/
function _convertToSpentAndReceivedItems(
BasicOrderParameters calldata parameters,
ItemType offerItemType,
ItemType considerationItemType
) internal pure returns (SpentItem[] memory, ReceivedItem[] memory) {
// Create the spent item.
SpentItem[] memory spentItems = new SpentItem[](1);
spentItems[0] = SpentItem({
itemType: offerItemType,
token: parameters.offerToken,
amount: parameters.offerAmount,
identifier: parameters.offerIdentifier
});
// Create the received item.
ReceivedItem[] memory receivedItems = new ReceivedItem[](
1 + parameters.additionalRecipients.length
);
address token = parameters.considerationToken;
uint256 amount = parameters.considerationAmount;
uint256 identifier = parameters.considerationIdentifier;
receivedItems[0] = ReceivedItem({
itemType: considerationItemType,
token: token,
amount: amount,
identifier: identifier,
recipient: parameters.offerer
});
// Iterate through the additional recipients and create the received
// items.
for (uint256 i = 0; i < parameters.additionalRecipients.length; i++) {
AdditionalRecipient calldata additionalRecipient = parameters
.additionalRecipients[i];
amount = additionalRecipient.amount;
receivedItems[i + 1] = ReceivedItem({
itemType: offerItemType == ItemType.ERC20
? ItemType.ERC20
: considerationItemType,
token: offerItemType == ItemType.ERC20
? parameters.offerToken
: token,
amount: amount,
identifier: offerItemType == ItemType.ERC20 ? 0 : identifier,
recipient: additionalRecipient.recipient
});
}
// Return the spent and received items.
return (spentItems, receivedItems);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ReceivedItem,
SpentItem
} from "seaport-types/src/lib/ConsiderationStructs.sol";
contract ReferenceGenerateOrderReturndataDecoder {
function decode(
bytes calldata returnedBytes
) external pure returns (SpentItem[] memory, ReceivedItem[] memory) {
return abi.decode(returnedBytes, (SpentItem[], ReceivedItem[]));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.7;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* 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`.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ConduitBatch1155Transfer,
ConduitTransfer
} from "../conduit/lib/ConduitStructs.sol";
/**
* @title ConduitInterface
* @author 0age
* @notice ConduitInterface contains all external function interfaces, events,
* and errors for conduit contracts.
*/
interface ConduitInterface {
/**
* @dev Revert with an error when attempting to execute transfers using a
* caller that does not have an open channel.
*/
error ChannelClosed(address channel);
/**
* @dev Revert with an error when attempting to update a channel to the
* current status of that channel.
*/
error ChannelStatusAlreadySet(address channel, bool isOpen);
/**
* @dev Revert with an error when attempting to execute a transfer for an
* item that does not have an ERC20/721/1155 item type.
*/
error InvalidItemType();
/**
* @dev Revert with an error when attempting to update the status of a
* channel from a caller that is not the conduit controller.
*/
error InvalidController();
/**
* @dev Emit an event whenever a channel is opened or closed.
*
* @param channel The channel that has been updated.
* @param open A boolean indicating whether the conduit is open or not.
*/
event ChannelUpdated(address indexed channel, bool open);
/**
* @notice Execute a sequence of ERC20/721/1155 transfers. Only a caller
* with an open channel can call this function.
*
* @param transfers The ERC20/721/1155 transfers to perform.
*
* @return magicValue A magic value indicating that the transfers were
* performed successfully.
*/
function execute(
ConduitTransfer[] calldata transfers
) external returns (bytes4 magicValue);
/**
* @notice Execute a sequence of batch 1155 transfers. Only a caller with an
* open channel can call this function.
*
* @param batch1155Transfers The 1155 batch transfers to perform.
*
* @return magicValue A magic value indicating that the transfers were
* performed successfully.
*/
function executeBatch1155(
ConduitBatch1155Transfer[] calldata batch1155Transfers
) external returns (bytes4 magicValue);
/**
* @notice Execute a sequence of transfers, both single and batch 1155. Only
* a caller with an open channel can call this function.
*
* @param standardTransfers The ERC20/721/1155 transfers to perform.
* @param batch1155Transfers The 1155 batch transfers to perform.
*
* @return magicValue A magic value indicating that the transfers were
* performed successfully.
*/
function executeWithBatch1155(
ConduitTransfer[] calldata standardTransfers,
ConduitBatch1155Transfer[] calldata batch1155Transfers
) external returns (bytes4 magicValue);
/**
* @notice Open or close a given channel. Only callable by the controller.
*
* @param channel The channel to open or close.
* @param isOpen The status of the channel (either open or closed).
*/
function updateChannel(address channel, bool isOpen) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import { ZoneParameters, Schema } from "../lib/ConsiderationStructs.sol";
import { IERC165 } from "./IERC165.sol";
/**
* @title ZoneInterface
* @notice Contains functions exposed by a zone.
*/
interface ZoneInterface is IERC165 {
/**
* @dev Authorizes an order before any token fulfillments from any order
* have been executed by Seaport.
*
* @param zoneParameters The context about the order fulfillment and any
* supplied extraData.
*
* @return authorizedOrderMagicValue The magic value that indicates a valid
* order.
*/
function authorizeOrder(
ZoneParameters calldata zoneParameters
) external returns (bytes4 authorizedOrderMagicValue);
/**
* @dev Validates an order after all token fulfillments for all orders have
* been executed by Seaport.
*
* @param zoneParameters The context about the order fulfillment and any
* supplied extraData.
*
* @return validOrderMagicValue The magic value that indicates a valid
* order.
*/
function validateOrder(
ZoneParameters calldata zoneParameters
) external returns (bytes4 validOrderMagicValue);
/**
* @dev Returns the metadata for this zone.
*
* @return name The name of the zone.
* @return schemas The schemas that the zone implements.
*/
function getSeaportMetadata()
external
view
returns (string memory name, Schema[] memory schemas); // map to SIP IDs
/**
* @dev Returns a boolean indicating if a given interface is supported in
* accordance with ERC-165.
*
* @param interfaceId the ERC-165 interface ID.
*
* @return a boolean indicating whether the interface is supported.
*/
function supportsInterface(
bytes4 interfaceId
) external view override returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @title ZoneInteractionErrors
* @author 0age
* @notice ZoneInteractionErrors contains errors related to zone interaction.
*/
interface ZoneInteractionErrors {
/**
* @dev Revert with an error when attempting to fill an order that specifies
* a restricted submitter as its order type when not submitted by
* either the offerer or the order's zone or approved as valid by the
* zone in question via a call to `isValidOrder`.
*
* @param orderHash The order hash for the invalid restricted order.
*/
error InvalidRestrictedOrder(bytes32 orderHash);
/**
* @dev Revert with an error when attempting to fill a contract order that
* fails to generate an order successfully, that does not adhere to the
* requirements for minimum spent or maximum received supplied by the
* fulfiller, or that fails the post-execution `ratifyOrder` check..
*
* @param orderHash The order hash for the invalid contract order.
*/
error InvalidContractOrder(bytes32 orderHash);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import { OrderStatus } from "seaport-types/src/lib/ConsiderationStructs.sol";
import { ReferenceAssertions } from "./ReferenceAssertions.sol";
import {
ReferenceSignatureVerification
} from "./ReferenceSignatureVerification.sol";
/**
* @title Verifiers
* @author 0age
* @notice Verifiers contains functions for performing verifications.
*/
contract ReferenceVerifiers is
ReferenceAssertions,
ReferenceSignatureVerification
{
/**
* @dev Derive and set hashes, reference chainId, and associated domain
* separator during deployment.
*
* @param conduitController A contract that deploys conduits, or proxies
* that may optionally be used to transfer approved
* ERC20/721/1155 tokens.
*/
constructor(
address conduitController
) ReferenceAssertions(conduitController) {}
/**
* @dev Internal view function to ensure that the current time falls within
* an order's valid timespan.
*
* @param startTime The time at which the order becomes active.
* @param endTime The time at which the order becomes inactive.
* @param revertOnInvalid A boolean indicating whether to revert if the
* order is not active.
*
* @return valid A boolean indicating whether the order is active.
*/
function _verifyTime(
uint256 startTime,
uint256 endTime,
bool revertOnInvalid
) internal view returns (bool valid) {
// Revert if order's timespan hasn't started yet or has already ended.
if (startTime > block.timestamp || endTime <= block.timestamp) {
// Only revert if revertOnInvalid has been supplied as true.
if (revertOnInvalid) {
revert InvalidTime(startTime, endTime);
}
// Return false as the order is invalid.
return false;
}
// Return true as the order time is valid.
valid = true;
}
/**
* @dev Internal view function to verify the signature of an order. An
* ERC-1271 fallback will be attempted if either the signature length
* is not 64 or 65 bytes or if the recovered signer does not match the
* supplied offerer. Note that in cases where a 64 or 65 byte signature
* is supplied, only standard ECDSA signatures that recover to a
* non-zero address are supported.
*
* @param offerer The offerer for the order.
* @param orderHash The order hash.
* @param signature A signature from the offerer indicating that the order
* has been approved.
*/
function _verifySignature(
address offerer,
bytes32 orderHash,
bytes memory signature
) internal view {
// Skip signature verification if the offerer is the caller.
if (offerer == msg.sender) {
return;
}
bytes32 domainSeparator = _domainSeparator();
// Derive original EIP-712 digest using domain separator and order hash.
bytes32 originalDigest = _deriveEIP712Digest(
domainSeparator,
orderHash
);
bytes32 digest;
bytes memory extractedSignature;
if (_isValidBulkOrderSize(signature)) {
// Rederive order hash and digest using bulk order proof.
(orderHash, extractedSignature) = _computeBulkOrderProof(
signature,
orderHash
);
digest = _deriveEIP712Digest(domainSeparator, orderHash);
} else {
digest = originalDigest;
extractedSignature = signature;
}
// Ensure that the signature for the digest is valid for the offerer.
_assertValidSignature(
offerer,
digest,
originalDigest,
signature,
extractedSignature
);
}
/**
* @dev Determines whether the specified bulk order size is valid.
*
* @param signature The signature of the bulk order to check.
*
* @return validLength True if bulk order size is valid, false otherwise.
*/
function _isValidBulkOrderSize(
bytes memory signature
) internal pure returns (bool validLength) {
validLength =
signature.length < 837 &&
signature.length > 98 &&
((signature.length - 67) % 32) < 2;
}
/**
* @dev Computes the bulk order hash for the specified proof and leaf. Note
* that if an index that exceeds the number of orders in the bulk order
* payload will instead "wrap around" and refer to an earlier index.
*
* @param proofAndSignature The proof and signature of the bulk order.
* @param leaf The leaf of the bulk order tree.
*
* @return bulkOrderHash The bulk order hash.
* @return signature The signature of the bulk order.
*/
function _computeBulkOrderProof(
bytes memory proofAndSignature,
bytes32 leaf
) internal view returns (bytes32 bulkOrderHash, bytes memory signature) {
bytes32 root = leaf;
// proofAndSignature with odd length is a compact signature (64 bytes).
uint256 length = proofAndSignature.length % 2 == 0 ? 65 : 64;
// Create a new array of bytes equal to the length of the signature.
signature = new bytes(length);
// Iterate over each byte in the signature.
for (uint256 i = 0; i < length; ++i) {
// Assign the byte from the proofAndSignature to the signature.
signature[i] = proofAndSignature[i];
}
// Compute the key by extracting the next three bytes from the
// proofAndSignature.
uint256 key = (((uint256(uint8(proofAndSignature[length])) << 16) |
((uint256(uint8(proofAndSignature[length + 1]))) << 8)) |
(uint256(uint8(proofAndSignature[length + 2]))));
uint256 height = (proofAndSignature.length - length) / 32;
// Create an array of bytes32 to hold the proof elements.
bytes32[] memory proofElements = new bytes32[](height);
// Iterate over each proof element.
for (uint256 elementIndex = 0; elementIndex < height; ++elementIndex) {
// Compute the starting index for the current proof element.
uint256 start = (length + 3) + (elementIndex * 32);
// Create a new array of bytes to hold the current proof element.
bytes memory buffer = new bytes(32);
// Iterate over each byte in the proof element.
for (uint256 i = 0; i < 32; ++i) {
// Assign the byte from the proofAndSignature to the buffer.
buffer[i] = proofAndSignature[start + i];
}
// Decode the current proof element from the buffer and assign it to
// the proofElements array.
proofElements[elementIndex] = abi.decode(buffer, (bytes32));
}
// Iterate over each proof element.
for (uint256 i = 0; i < proofElements.length; ++i) {
// Retrieve the proof element.
bytes32 proofElement = proofElements[i];
// Check if the current bit of the key is set.
if ((key >> i) % 2 == 0) {
// If the current bit is not set, then concatenate the root and
// the proof element, and compute the keccak256 hash of the
// concatenation to assign it to the root.
root = keccak256(abi.encodePacked(root, proofElement));
} else {
// If the current bit is set, then concatenate the proof element
// and the root, and compute the keccak256 hash of the
// concatenation to assign it to the root.
root = keccak256(abi.encodePacked(proofElement, root));
}
}
// Compute the bulk order hash and return it.
bulkOrderHash = keccak256(
abi.encodePacked(_bulkOrderTypehashes[height], root)
);
// Return the signature.
return (bulkOrderHash, signature);
}
/**
* @dev Internal view function to validate that a given order is fillable
* and not cancelled based on the order status.
*
* @param orderHash The order hash.
* @param orderStatus The status of the order, including whether it has
* been cancelled and the fraction filled.
* @param onlyAllowUnused A boolean flag indicating whether partial fills
* are supported by the calling function.
* @param revertOnInvalid A boolean indicating whether to revert if the
* order has been cancelled or filled beyond the
* allowable amount.
*
* @return valid A boolean indicating whether the order is valid.
*/
function _verifyOrderStatus(
bytes32 orderHash,
OrderStatus storage orderStatus,
bool onlyAllowUnused,
bool revertOnInvalid
) internal view returns (bool valid) {
// Ensure that the order has not been cancelled.
if (orderStatus.isCancelled) {
// Only revert if revertOnInvalid has been supplied as true.
if (revertOnInvalid) {
revert OrderIsCancelled(orderHash);
}
// Return false as the order status is invalid.
return false;
}
// Read order status numerator from storage and place on stack.
uint256 orderStatusNumerator = orderStatus.numerator;
// If the order is not entirely unused...
if (orderStatusNumerator != 0) {
// ensure the order has not been partially filled when not allowed.
if (onlyAllowUnused) {
// Always revert on partial fills when onlyAllowUnused is true.
revert OrderPartiallyFilled(orderHash);
// Otherwise, ensure that order has not been entirely filled.
} else if (orderStatusNumerator >= orderStatus.denominator) {
// Only revert if revertOnInvalid has been supplied as true.
if (revertOnInvalid) {
revert OrderAlreadyFilled(orderHash);
}
// Return false as the order status is invalid.
return false;
}
}
// Return true as the order status is valid.
valid = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ERC20Interface,
ERC721Interface,
ERC1155Interface
} from "seaport-types/src/interfaces/AbridgedTokenInterfaces.sol";
import {
TokenTransferrerErrors
} from "seaport-types/src/interfaces/TokenTransferrerErrors.sol";
contract ReferenceTokenTransferrer is TokenTransferrerErrors {
/**
* @dev Internal function to transfer ERC20 tokens from a given originator
* to a given recipient. Sufficient approvals must be set on the
* contract performing the transfer.
*
* @param token The ERC20 token to transfer.
* @param from The originator of the transfer.
* @param to The recipient of the transfer.
* @param amount The amount to transfer.
*/
function _performERC20Transfer(
address token,
address from,
address to,
uint256 amount
) internal {
// If the provided token is not a contract, revert.
if (token.code.length == 0) {
revert NoContract(token);
}
// Attempt to transfer the tokens.
(bool ok, bytes memory data) = token.call(
abi.encodeWithSelector(
ERC20Interface.transferFrom.selector,
from,
to,
amount
)
);
// NOTE: revert reasons are not "bubbled up" at the moment
if (!ok) {
revert TokenTransferGenericFailure(token, from, to, 0, amount);
}
// If the token does not return a boolean, revert.
if (data.length != 0 && data.length >= 32) {
if (!abi.decode(data, (bool))) {
revert BadReturnValueFromERC20OnTransfer(
token,
from,
to,
amount
);
}
}
}
/**
* @dev Internal function to transfer an ERC721 token from a given
* originator to a given recipient. Sufficient approvals must be set on
* the contract performing the transfer.
*
* @param token The ERC721 token to transfer.
* @param from The originator of the transfer.
* @param to The recipient of the transfer.
* @param identifier The tokenId to transfer.
*/
function _performERC721Transfer(
address token,
address from,
address to,
uint256 identifier
) internal {
// If the provided token is not a contract, revert.
if (token.code.length == 0) {
revert NoContract(token);
}
ERC721Interface(token).transferFrom(from, to, identifier);
}
/**
* @dev Internal function to transfer ERC1155 tokens from a given
* originator to a given recipient. Sufficient approvals must be set on
* the contract performing the transfer and contract recipients must
* implement onReceived to indicate that they are willing to accept the
* transfer.
*
* @param token The ERC1155 token to transfer.
* @param from The originator of the transfer.
* @param to The recipient of the transfer.
* @param identifier The id to transfer.
* @param amount The amount to transfer.
*/
function _performERC1155Transfer(
address token,
address from,
address to,
uint256 identifier,
uint256 amount
) internal {
// If the provided token is not a contract, revert.
if (token.code.length == 0) {
revert NoContract(token);
}
ERC1155Interface(token).safeTransferFrom(
from,
to,
identifier,
amount,
""
);
}
/**
* @dev Internal function to transfer ERC1155 tokens from a given
* originator to a given recipient. Sufficient approvals must be set on
* the contract performing the transfer and contract recipients must
* implement onReceived to indicate that they are willing to accept the
* transfer.
*
* @param token The ERC1155 token to transfer in batch.
* @param from The originator of the transfer batch.
* @param to The recipient of the transfer batch.
* @param identifiers The ids to transfer.
* @param amounts The amounts to transfer.
*/
function _performERC1155BatchTransfer(
address token,
address from,
address to,
uint256[] memory identifiers,
uint256[] memory amounts
) internal {
// If the provided token is not a contract, revert.
if (token.code.length == 0) {
revert NoContract(token);
}
ERC1155Interface(token).safeBatchTransferFrom(
from,
to,
identifiers,
amounts,
""
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
OrderParameters
} from "seaport-types/src/lib/ConsiderationStructs.sol";
import { ReferenceGettersAndDerivers } from "./ReferenceGettersAndDerivers.sol";
import {
TokenTransferrerErrors
} from "seaport-types/src/interfaces/TokenTransferrerErrors.sol";
import { ReferenceCounterManager } from "./ReferenceCounterManager.sol";
/**
* @title Assertions
* @author 0age
* @notice Assertions contains logic for making various assertions that do not
* fit neatly within a dedicated semantic scope.
*/
contract ReferenceAssertions is
ReferenceGettersAndDerivers,
ReferenceCounterManager,
TokenTransferrerErrors
{
/**
* @dev Derive and set hashes, reference chainId, and associated domain
* separator during deployment.
*
* @param conduitController A contract that deploys conduits, or proxies
* that may optionally be used to transfer approved
* ERC20/721/1155 tokens.
*/
constructor(
address conduitController
) ReferenceGettersAndDerivers(conduitController) {}
/**
* @dev Internal view function to ensure that the supplied consideration
* array length on a given set of order parameters is not less than the
* original consideration array length for that order and to retrieve
* the current counter for a given order's offerer and zone and use it
* to derive the order hash.
*
* @param orderParameters The parameters of the order to hash.
*
* @return orderHash The order hash.
*/
function _assertConsiderationLengthAndGetOrderHash(
OrderParameters memory orderParameters
) internal view returns (bytes32 orderHash) {
// Ensure supplied consideration array length is not less than original.
_assertConsiderationLengthIsNotLessThanOriginalConsiderationLength(
orderParameters.consideration.length,
orderParameters.totalOriginalConsiderationItems
);
// Derive and return order hash using current counter for the offerer.
orderHash = _deriveOrderHash(
orderParameters,
_getCounter(orderParameters.offerer)
);
}
/**
* @dev Internal pure function to ensure that the supplied consideration
* array length for an order to be fulfilled is not less than the
* original consideration array length for that order.
*
* @param suppliedConsiderationItemTotal The number of consideration items
* supplied when fulfilling the order.
* @param originalConsiderationItemTotal The number of consideration items
* supplied on initial order creation.
*/
function _assertConsiderationLengthIsNotLessThanOriginalConsiderationLength(
uint256 suppliedConsiderationItemTotal,
uint256 originalConsiderationItemTotal
) internal pure {
// Ensure supplied consideration array length is not less than original.
if (suppliedConsiderationItemTotal < originalConsiderationItemTotal) {
revert MissingOriginalConsiderationItems();
}
}
/**
* @dev Internal pure function to ensure that a given item amount in not
* zero.
*
* @param amount The amount to check.
*/
function _assertNonZeroAmount(uint256 amount) internal pure {
if (amount == 0) {
revert MissingItemAmount();
}
}
/**
* @dev Internal pure function to validate calldata offsets for dynamic
* types in BasicOrderParameters and other parameters. This ensures
* that functions using the calldata object normally will be using the
* same data as the assembly functions and that values that are bound
* to a given range are within that range. Note that no parameters are
* supplied as all basic order functions use the same calldata
* encoding.
*/
function _assertValidBasicOrderParameters() internal pure {
/*
* Checks:
* 1. Order parameters struct offset == 0x20
* 2. Additional recipients arr offset == 0x200
* 3. Signature offset == 0x240 + (recipients.length * 0x40)
* 4. BasicOrderType between 0 and 23 (i.e. < 24)
*/
// Declare a boolean designating basic order parameter offset validity.
bool validOffsets = (abi.decode(msg.data[4:36], (uint256)) == 32 &&
abi.decode(msg.data[548:580], (uint256)) == 576 &&
abi.decode(msg.data[580:612], (uint256)) ==
608 + 64 * abi.decode(msg.data[612:644], (uint256))) &&
abi.decode(msg.data[292:324], (uint256)) < 24;
// Revert with an error if basic order parameter offsets are invalid.
if (!validOffsets) {
revert InvalidBasicOrderParameterEncoding();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
EIP1271Interface
} from "seaport-types/src/interfaces/EIP1271Interface.sol";
import {
SignatureVerificationErrors
} from "seaport-types/src/interfaces/SignatureVerificationErrors.sol";
import {
EIP2098_allButHighestBitMask
} from "seaport-types/src/lib/ConsiderationConstants.sol";
/**
* @title SignatureVerification
* @author 0age
* @notice SignatureVerification contains logic for verifying signatures.
*/
contract ReferenceSignatureVerification is SignatureVerificationErrors {
/**
* @dev Internal view function to verify the signature of an order. An
* ERC-1271 fallback will be attempted if either the signature length
* is not 64 or 65 bytes or if the recovered signer does not match the
* supplied signer. Note that in cases where a 64 or 65 byte signature
* is supplied, only standard ECDSA signatures that recover to a
* non-zero address are supported.
*
* @param signer The signer for the order.
* @param digest The digest to verify signature against.
* @param originalDigest The original digest to verify signature against.
* @param originalSignature The original signature.
* @param signature A signature from the signer indicating that the
* order has been approved.
*/
function _assertValidSignature(
address signer,
bytes32 digest,
bytes32 originalDigest,
bytes memory originalSignature,
bytes memory signature
) internal view {
// Declare r, s, and v signature parameters.
bytes32 r;
bytes32 s;
uint8 v;
if (signer.code.length > 0) {
// If signer is a contract, try verification via EIP-1271.
_assertValidEIP1271Signature(
signer,
originalDigest,
originalSignature
);
// Return early if the ERC-1271 signature check succeeded.
return;
} else if (signature.length == 64) {
// If signature contains 64 bytes, parse as EIP-2098 sig. (r+s&v)
// Declare temporary vs that will be decomposed into s and v.
bytes32 vs;
// Decode signature into r, vs.
(r, vs) = abi.decode(signature, (bytes32, bytes32));
// Decompose vs into s and v.
s = vs & EIP2098_allButHighestBitMask;
// If the highest bit is set, v = 28, otherwise v = 27.
v = uint8(uint256(vs >> 255)) + 27;
} else if (signature.length == 65) {
(r, s) = abi.decode(signature, (bytes32, bytes32));
v = uint8(signature[64]);
// Ensure v value is properly formatted.
if (v != 27 && v != 28) {
revert BadSignatureV(v);
}
} else {
revert InvalidSignature();
}
// Attempt to recover signer using the digest and signature parameters.
address recoveredSigner = ecrecover(digest, v, r, s);
// Disallow invalid signers.
if (recoveredSigner == address(0) || recoveredSigner != signer) {
revert InvalidSigner();
// Should a signer be recovered, but it doesn't match the signer...
}
}
/**
* @dev Internal view function to verify the signature of an order using
* ERC-1271 (i.e. contract signatures via `isValidSignature`).
*
* @param signer The signer for the order.
* @param digest The signature digest, derived from the domain separator
* and the order hash.
* @param signature A signature (or other data) used to validate the digest.
*/
function _assertValidEIP1271Signature(
address signer,
bytes32 digest,
bytes memory signature
) internal view {
if (
EIP1271Interface(signer).isValidSignature(digest, signature) !=
EIP1271Interface.isValidSignature.selector
) {
revert BadContractSignature();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @title ERC20Interface
* @notice Contains the minimum interfaces needed to interact with ERC20s.
*/
interface ERC20Interface {
/**
* @dev Allows an operator to transfer tokens on behalf of an owner.
*
* @param from The address of the owner.
* @param to The address of the recipient.
* @param value The amount of tokens to transfer.
*
* @return success True if the transfer was successful.
*/
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
/**
* @dev Allows an operator to approve a spender to transfer tokens on behalf
* of a user.
*
* @param spender The address of the spender.
* @param value The amount of tokens to approve.
*
* @return success True if the approval was successful.
*/
function approve(
address spender,
uint256 value
) external returns (bool success);
/**
* @dev Returns the balance of a user.
*
* @param account The address of the user.
*
* @return balance The balance of the user.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Returns the amount which spender is still allowed to withdraw
* from owner.
*
* @param owner The address of the owner.
* @param spender The address of the spender.
*
* @return remaining The amount of tokens that the spender is allowed to
* transfer on behalf of the owner.
*/
function allowance(
address owner,
address spender
) external view returns (uint256 remaining);
}
/**
* @title ERC721Interface
* @notice Contains the minimum interfaces needed to interact with ERC721s.
*/
interface ERC721Interface {
/**
* @dev Allows an operator to transfer tokens on behalf of an owner.
*
* @param from The address of the owner.
* @param to The address of the recipient.
* @param tokenId The ID of the token to transfer.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Allows an owner to approve an operator to transfer all tokens on a
* contract on behalf of the owner.
*
* @param to The address of the operator.
* @param approved Whether the operator is approved.
*/
function setApprovalForAll(address to, bool approved) external;
/**
* @dev Returns the account approved for tokenId token
*
* @param tokenId The tokenId to query the approval of.
*
* @return operator The approved account of the tokenId.
*/
function getApproved(
uint256 tokenId
) external view returns (address operator);
/**
* @dev Returns whether an operator is allowed to manage all of
* the assets of owner.
*
* @param owner The address of the owner.
* @param operator The address of the operator.
*
* @return approved True if the operator is approved by the owner.
*/
function isApprovedForAll(
address owner,
address operator
) external view returns (bool);
/**
* @dev Returns the owner of a given token ID.
*
* @param tokenId The token ID.
*
* @return owner The owner of the token.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
}
/**
* @title ERC1155Interface
* @notice Contains the minimum interfaces needed to interact with ERC1155s.
*/
interface ERC1155Interface {
/**
* @dev Allows an operator to transfer tokens on behalf of an owner.
*
* @param from The address of the owner.
* @param to The address of the recipient.
* @param id The ID of the token(s) to transfer.
* @param amount The amount of tokens to transfer.
* @param data Additional data.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Allows an operator to transfer tokens on behalf of an owner.
*
* @param from The address of the owner.
* @param to The address of the recipient.
* @param ids The IDs of the token(s) to transfer.
* @param amounts The amounts of tokens to transfer.
* @param data Additional data.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
/**
* @dev Allows an owner to approve an operator to transfer all tokens on a
* contract on behalf of the owner.
*
* @param to The address of the operator.
* @param approved Whether the operator is approved.
*/
function setApprovalForAll(address to, bool approved) external;
/**
* @dev Returns the amount of token type id owned by account.
*
* @param account The address of the account.
* @param id The id of the token.
*
* @return balance The amount of tokens of type id owned by account.
*/
function balanceOf(
address account,
uint256 id
) external view returns (uint256);
/**
* @dev Returns true if operator is approved to transfer account's tokens.
*
* @param account The address of the account.
* @param operator The address of the operator.
*
* @return approved True if the operator is approved to transfer account's
* tokens.
*/
function isApprovedForAll(
address account,
address operator
) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {ConsiderationItem, OfferItem, OrderParameters} from "seaport-types/src/lib/ConsiderationStructs.sol";
import {ReferenceConsiderationBase} from "./ReferenceConsiderationBase.sol";
/**
* @title GettersAndDerivers
* @author 0age
* @notice ConsiderationInternal contains pure and internal view functions
* related to getting or deriving various values.
*/
contract ReferenceGettersAndDerivers is ReferenceConsiderationBase {
/**
* @dev Derive and set hashes, reference chainId, and associated domain
* separator during deployment.
*
* @param conduitController A contract that deploys conduits, or proxies
* that may optionally be used to transfer approved
* ERC20/721/1155 tokens.
*/
constructor(
address conduitController
) ReferenceConsiderationBase(conduitController) {}
/**
* @dev Internal view function to derive the EIP-712 hash for an offer item.
*
* @param offerItem The offered item to hash.
*
* @return The hash.
*/
function _hashOfferItem(
OfferItem memory offerItem
) internal view returns (bytes32) {
return
keccak256(
abi.encode(
_OFFER_ITEM_TYPEHASH,
offerItem.itemType,
offerItem.token,
offerItem.identifierOrCriteria,
offerItem.startAmount,
offerItem.endAmount
)
);
}
/**
* @dev Internal view function to derive the EIP-712 hash for a
* consideration item.
*
* @param considerationItem The consideration item to hash.
*
* @return The hash.
*/
function _hashConsiderationItem(
ConsiderationItem memory considerationItem
) internal view returns (bytes32) {
return
keccak256(
abi.encode(
_CONSIDERATION_ITEM_TYPEHASH,
considerationItem.itemType,
considerationItem.token,
considerationItem.identifierOrCriteria,
considerationItem.startAmount,
considerationItem.endAmount,
considerationItem.recipient
)
);
}
/**
* @dev Internal view function to derive the order hash for a given order.
* Note that only the original consideration items are included in the
* order hash, as additional consideration items may be supplied by the
* caller.
*
* @param orderParameters The parameters of the order to hash.
* @param counter The counter of the order to hash.
*
* @return orderHash The hash.
*/
function _deriveOrderHash(
OrderParameters memory orderParameters,
uint256 counter
) internal view returns (bytes32 orderHash) {
// Designate new memory regions for offer and consideration item hashes.
bytes32[] memory offerHashes = new bytes32[](
orderParameters.offer.length
);
bytes32[] memory considerationHashes = new bytes32[](
orderParameters.totalOriginalConsiderationItems
);
// Iterate over each offer on the order.
for (uint256 i = 0; i < orderParameters.offer.length; ++i) {
// Hash the offer and place the result into memory.
offerHashes[i] = _hashOfferItem(orderParameters.offer[i]);
}
// Iterate over each consideration on the order.
for (
uint256 i = 0;
i < orderParameters.totalOriginalConsiderationItems;
++i
) {
// Hash the consideration and place the result into memory.
considerationHashes[i] = _hashConsiderationItem(
orderParameters.consideration[i]
);
}
// Derive and return the order hash as specified by EIP-712.
return
keccak256(
abi.encode(
_ORDER_TYPEHASH,
orderParameters.offerer,
orderParameters.zone,
keccak256(abi.encodePacked(offerHashes)),
keccak256(abi.encodePacked(considerationHashes)),
orderParameters.orderType,
orderParameters.startTime,
orderParameters.endTime,
orderParameters.zoneHash,
orderParameters.salt,
orderParameters.conduitKey,
counter
)
);
}
/**
* @dev Internal pure function to efficiently derive an digest to sign for
* an order in accordance with EIP-712.
*
* @param domainSeparator The domain separator.
* @param orderHash The order hash.
*
* @return value The hash.
*/
function _deriveEIP712Digest(
bytes32 domainSeparator,
bytes32 orderHash
) internal pure returns (bytes32 value) {
value = keccak256(
abi.encodePacked(uint16(0x1901), domainSeparator, orderHash)
);
}
/**
* @dev Internal view function to derive the address of a given conduit
* using a corresponding conduit key.
*
* @param conduitKey A bytes32 value indicating what corresponding conduit,
* if any, to source token approvals from. This value is
* the "salt" parameter supplied by the deployer (i.e. the
* conduit controller) when deploying the given conduit.
*
* @return conduit The address of the conduit associated with the given
* conduit key.
*/
function _deriveConduit(
bytes32 conduitKey
) internal view returns (address conduit) {
// Derive the conduit address
bytes32 hash = keccak256(
bytes.concat(
keccak256("zksyncCreate2"),
bytes32(uint256(uint160(address(_CONDUIT_CONTROLLER)))),
conduitKey,
_CONDUIT_RUNTIME_CODE_HASH,
keccak256("")
)
);
conduit = address(uint160(uint256(hash)));
}
/**
* @dev Internal view function to get the EIP-712 domain separator. If the
* chainId matches the chainId set on deployment, the cached domain
* separator will be returned; otherwise, it will be derived from
* scratch.
*/
function _domainSeparator() internal view returns (bytes32) {
return
block.chainid == _CHAIN_ID
? _DOMAIN_SEPARATOR
: _deriveDomainSeparator(
_EIP_712_DOMAIN_TYPEHASH,
_NAME_HASH,
_VERSION_HASH
);
}
/**
* @notice Retrieve configuration information for this contract.
*
* @return version The contract version.
* @return domainSeparator The domain separator for this contract.
* @return conduitController The conduit Controller set for this contract.
*/
function _information()
internal
view
returns (
string memory version,
bytes32 domainSeparator,
address conduitController
)
{
version = _VERSION;
domainSeparator = _domainSeparator();
conduitController = address(_CONDUIT_CONTROLLER);
}
/**
* @notice Retrieve the name of this contract.
*
* @return The name of this contract.
*/
function _name() internal pure returns (string memory) {
// Return the name of the contract.
return _NAME;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ConsiderationEventsAndErrors
} from "seaport-types/src/interfaces/ConsiderationEventsAndErrors.sol";
import { ReferenceReentrancyGuard } from "./ReferenceReentrancyGuard.sol";
/**
* @title CounterManager
* @author 0age
* @notice CounterManager contains a storage mapping and related functionality
* for retrieving and incrementing a per-offerer counter.
*/
contract ReferenceCounterManager is
ConsiderationEventsAndErrors,
ReferenceReentrancyGuard
{
// Only orders signed using an offerer's current counter are fulfillable.
mapping(address => uint256) private _counters;
/**
* @dev Internal function to cancel all orders from a given offerer in bulk
* by incrementing a counter. Note that only the offerer may increment
* the counter. Note that the counter is incremented by a large,
* quasi-random interval, which makes it infeasible to "activate"
* signed orders by incrementing the counter. This activation
* functionality can be achieved instead with restricted orders or
* contract orders.
*
* @return newCounter The new counter.
*/
function _incrementCounter() internal returns (uint256 newCounter) {
// Use second half of the previous block hash as a quasi-random number.
uint256 quasiRandomNumber = uint256(blockhash(block.number - 1)) >> 128;
// Retrieve the original counter value.
uint256 originalCounter = _counters[msg.sender];
// Increment current counter for the supplied offerer.
newCounter = quasiRandomNumber + originalCounter;
// Update the counter with the new value.
_counters[msg.sender] = newCounter;
// Emit an event containing the new counter.
emit CounterIncremented(newCounter, msg.sender);
}
/**
* @dev Internal view function to retrieve the current counter for a given
* offerer.
*
* @param offerer The offerer in question.
*
* @return currentCounter The current counter.
*/
function _getCounter(
address offerer
) internal view returns (uint256 currentCounter) {
// Return the counter for the supplied offerer.
currentCounter = _counters[offerer];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @title SignatureVerificationErrors
* @author 0age
* @notice SignatureVerificationErrors contains all errors related to signature
* verification.
*/
interface SignatureVerificationErrors {
/**
* @dev Revert with an error when a signature that does not contain a v
* value of 27 or 28 has been supplied.
*
* @param v The invalid v value.
*/
error BadSignatureV(uint8 v);
/**
* @dev Revert with an error when the signer recovered by the supplied
* signature does not match the offerer or an allowed EIP-1271 signer
* as specified by the offerer in the event they are a contract.
*/
error InvalidSigner();
/**
* @dev Revert with an error when a signer cannot be recovered from the
* supplied signature.
*/
error InvalidSignature();
/**
* @dev Revert with an error when an EIP-1271 call to an account fails.
*/
error BadContractSignature();
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @title EIP1271Interface
* @notice Interface for the EIP-1271 standard signature validation method for
* contracts.
*/
interface EIP1271Interface {
/**
* @dev Validates a smart contract signature
*
* @param digest bytes32 The digest of the data to be signed.
* @param signature bytes The signature of the data to be validated.
*
* @return bytes4 The magic value, if the signature is valid.
*/
function isValidSignature(
bytes32 digest,
bytes calldata signature
) external view returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/*
* -------------------------- Disambiguation & Other Notes ---------------------
* - The term "head" is used as it is in the documentation for ABI encoding,
* but only in reference to dynamic types, i.e. it always refers to the
* offset or pointer to the body of a dynamic type. In calldata, the head
* is always an offset (relative to the parent object), while in memory,
* the head is always the pointer to the body. More information found here:
* https://docs.soliditylang.org/en/v0.8.17/abi-spec.html#argument-encoding
* - Note that the length of an array is separate from and precedes the
* head of the array.
*
* - The term "body" is used in place of the term "head" used in the ABI
* documentation. It refers to the start of the data for a dynamic type,
* e.g. the first word of a struct or the first word of the first element
* in an array.
*
* - The term "pointer" is used to describe the absolute position of a value
* and never an offset relative to another value.
* - The suffix "_ptr" refers to a memory pointer.
* - The suffix "_cdPtr" refers to a calldata pointer.
*
* - The term "offset" is used to describe the position of a value relative
* to some parent value. For example, OrderParameters_conduit_offset is the
* offset to the "conduit" value in the OrderParameters struct relative to
* the start of the body.
* - Note: Offsets are used to derive pointers.
*
* - Some structs have pointers defined for all of their fields in this file.
* Lines which are commented out are fields that are not used in the
* codebase but have been left in for readability.
*/
// Declare constants for name, version, and reentrancy sentinel values.
// Name is right padded, so it touches the length which is left padded. This
// enables writing both values at once. Length goes at byte 95 in memory, and
// name fills bytes 96-109, so both values can be written left-padded to 77.
uint256 constant NameLengthPtr = 0x4D;
uint256 constant NameWithLength = 0x0d436F6E73696465726174696F6E;
uint256 constant information_version_offset = 0;
uint256 constant information_version_cd_offset = 0x60;
uint256 constant information_domainSeparator_offset = 0x20;
uint256 constant information_conduitController_offset = 0x40;
uint256 constant information_versionLengthPtr = 0x63;
uint256 constant information_versionWithLength = 0x03312e36; // 1.6
uint256 constant information_length = 0xa0;
// uint256(uint32(bytes4(keccak256("_REENTRANCY_GUARD_SLOT"))))
uint256 constant _REENTRANCY_GUARD_SLOT = 0x929eee14;
/*
*
* --------------------------------------------------------------------------+
* Opcode | Mnemonic | Stack | Memory |
* --------------------------------------------------------------------------|
* 60 0x02 | PUSH1 0x02 | 0x02 | |
* 60 0x1e | PUSH1 0x1e | 0x1e 0x02 | |
* 61 0x3d5c | PUSH2 0x3d5c | 0x3d5c 0x1e 0x02 | |
* 3d | RETURNDATASIZE | 0 0x3d5c 0x1e 0x02 | |
* |
* ::: store deployed bytecode in memory: (3d) RETURNDATASIZE (5c) TLOAD ::: |
* 52 | MSTORE | 0x1e 0x02 | [0..0x20): 0x3d5c |
* f3 | RETURN | | [0..0x20): 0x3d5c |
* --------------------------------------------------------------------------+
*/
uint256 constant _TLOAD_TEST_PAYLOAD = 0x6002_601e_613d5c_3d_52_f3;
uint256 constant _TLOAD_TEST_PAYLOAD_LENGTH = 0x0a;
uint256 constant _TLOAD_TEST_PAYLOAD_OFFSET = 0x16;
uint256 constant _NOT_ENTERED_TSTORE = 0;
uint256 constant _ENTERED_TSTORE = 1;
uint256 constant _ENTERED_AND_ACCEPTING_NATIVE_TOKENS_TSTORE = 2;
uint256 constant _TSTORE_ENABLED_SSTORE = 0;
uint256 constant _NOT_ENTERED_SSTORE = 1;
uint256 constant _ENTERED_SSTORE = 2;
uint256 constant _ENTERED_AND_ACCEPTING_NATIVE_TOKENS_SSTORE = 3;
uint256 constant Offset_fulfillAdvancedOrder_criteriaResolvers = 0x20;
uint256 constant Offset_fulfillAvailableOrders_offerFulfillments = 0x20;
uint256 constant Offset_fulfillAvailableOrders_considerationFulfillments = 0x40;
uint256 constant Offset_fulfillAvailableAdvancedOrders_criteriaResolvers = 0x20;
uint256 constant Offset_fulfillAvailableAdvancedOrders_offerFulfillments = 0x40;
uint256 constant Offset_fulfillAvailableAdvancedOrders_cnsdrationFlflmnts =
(0x60);
uint256 constant Offset_matchOrders_fulfillments = 0x20;
uint256 constant Offset_matchAdvancedOrders_criteriaResolvers = 0x20;
uint256 constant Offset_matchAdvancedOrders_fulfillments = 0x40;
// Common Offsets
// Offsets for identically positioned fields shared by:
// OfferItem, ConsiderationItem, SpentItem, ReceivedItem
uint256 constant Selector_length = 0x4;
uint256 constant Common_token_offset = 0x20;
uint256 constant Common_identifier_offset = 0x40;
uint256 constant Common_amount_offset = 0x60;
uint256 constant Common_endAmount_offset = 0x80;
uint256 constant SpentItem_size = 0x80;
uint256 constant SpentItem_size_shift = 0x7;
uint256 constant OfferItem_size = 0xa0;
uint256 constant OfferItem_size_with_head_pointer = 0xc0;
uint256 constant ReceivedItem_size_excluding_recipient = 0x80;
uint256 constant ReceivedItem_size = 0xa0;
uint256 constant ReceivedItem_amount_offset = 0x60;
uint256 constant ReceivedItem_recipient_offset = 0x80;
uint256 constant ReceivedItem_CommonParams_size = 0x60;
uint256 constant ConsiderationItem_size = 0xc0;
uint256 constant ConsiderationItem_size_with_head_pointer = 0xe0;
uint256 constant ConsiderationItem_recipient_offset = 0xa0;
// Store the same constant in an abbreviated format for a line length fix.
uint256 constant ConsiderItem_recipient_offset = 0xa0;
uint256 constant Execution_offerer_offset = 0x20;
uint256 constant Execution_conduit_offset = 0x40;
// uint256 constant OrderParameters_offerer_offset = 0x00;
uint256 constant OrderParameters_zone_offset = 0x20;
uint256 constant OrderParameters_offer_head_offset = 0x40;
uint256 constant OrderParameters_consideration_head_offset = 0x60;
// uint256 constant OrderParameters_orderType_offset = 0x80;
uint256 constant OrderParameters_startTime_offset = 0xa0;
uint256 constant OrderParameters_endTime_offset = 0xc0;
uint256 constant OrderParameters_zoneHash_offset = 0xe0;
uint256 constant OrderParameters_salt_offset = 0x100;
uint256 constant OrderParameters_conduit_offset = 0x120;
uint256 constant OrderParameters_counter_offset = 0x140;
uint256 constant Fulfillment_itemIndex_offset = 0x20;
uint256 constant AdvancedOrder_head_size = 0xa0;
uint256 constant AdvancedOrder_numerator_offset = 0x20;
uint256 constant AdvancedOrder_denominator_offset = 0x40;
uint256 constant AdvancedOrder_signature_offset = 0x60;
uint256 constant AdvancedOrder_extraData_offset = 0x80;
uint256 constant OrderStatus_ValidatedAndNotCancelled = 1;
uint256 constant OrderStatus_filledNumerator_offset = 0x10;
uint256 constant OrderStatus_filledDenominator_offset = 0x88;
uint256 constant OrderStatus_ValidatedAndNotCancelledAndFullyFilled = (
0x0000000000000000000000000000010000000000000000000000000000010001
);
uint256 constant ThirtyOneBytes = 0x1f;
uint256 constant OneWord = 0x20;
uint256 constant TwoWords = 0x40;
uint256 constant ThreeWords = 0x60;
uint256 constant FourWords = 0x80;
uint256 constant FiveWords = 0xa0;
uint256 constant OneWordShift = 0x5;
uint256 constant TwoWordsShift = 0x6;
uint256 constant SixtyThreeBytes = 0x3f;
uint256 constant OnlyFullWordMask = 0xffffffe0;
uint256 constant FreeMemoryPointerSlot = 0x40;
uint256 constant ZeroSlot = 0x60;
uint256 constant DefaultFreeMemoryPointer = 0x80;
uint256 constant Slot0x80 = 0x80;
uint256 constant Slot0xA0 = 0xa0;
uint256 constant BasicOrder_common_params_size = 0xa0;
uint256 constant BasicOrder_considerationHashesArray_ptr = 0x160;
uint256 constant BasicOrder_receivedItemByteMap =
(0x0000010102030000000000000000000000000000000000000000000000000000);
uint256 constant BasicOrder_offeredItemByteMap =
(0x0203020301010000000000000000000000000000000000000000000000000000);
uint256 constant BasicOrder_consideration_offset_from_offer = 0xa0;
bytes32 constant OrdersMatchedTopic0 =
(0x4b9f2d36e1b4c93de62cc077b00b1a91d84b6c31b4a14e012718dcca230689e7);
uint256 constant EIP712_Order_size = 0x180;
uint256 constant EIP712_OfferItem_size = 0xc0;
uint256 constant EIP712_ConsiderationItem_size = 0xe0;
uint256 constant AdditionalRecipient_size = 0x40;
uint256 constant AdditionalRecipient_size_shift = 0x6;
uint256 constant EIP712_DomainSeparator_offset = 0x02;
uint256 constant EIP712_OrderHash_offset = 0x22;
uint256 constant EIP712_DigestPayload_size = 0x42;
uint256 constant EIP712_domainData_nameHash_offset = 0x20;
uint256 constant EIP712_domainData_versionHash_offset = 0x40;
uint256 constant EIP712_domainData_chainId_offset = 0x60;
uint256 constant EIP712_domainData_verifyingContract_offset = 0x80;
uint256 constant EIP712_domainData_size = 0xa0;
// Minimum BulkOrder proof size: 64 bytes for signature + 3 for key + 32 for 1
// sibling. Maximum BulkOrder proof size: 65 bytes for signature + 3 for key +
// 768 for 24 siblings.
uint256 constant BulkOrderProof_minSize = 0x63;
uint256 constant BulkOrderProof_rangeSize = 0x2e2;
uint256 constant BulkOrderProof_lengthAdjustmentBeforeMask = 0x1d;
uint256 constant BulkOrderProof_lengthRangeAfterMask = 0x2;
uint256 constant BulkOrderProof_keyShift = 0xe8;
uint256 constant BulkOrderProof_keySize = 0x3;
uint256 constant BulkOrder_Typehash_Height_One =
(0x3ca2711d29384747a8f61d60aad3c450405f7aaff5613541dee28df2d6986d32);
uint256 constant BulkOrder_Typehash_Height_Two =
(0xbf8e29b89f29ed9b529c154a63038ffca562f8d7cd1e2545dda53a1b582dde30);
uint256 constant BulkOrder_Typehash_Height_Three =
(0x53c6f6856e13104584dd0797ca2b2779202dc2597c6066a42e0d8fe990b0024d);
uint256 constant BulkOrder_Typehash_Height_Four =
(0xa02eb7ff164c884e5e2c336dc85f81c6a93329d8e9adf214b32729b894de2af1);
uint256 constant BulkOrder_Typehash_Height_Five =
(0x39c9d33c18e050dda0aeb9a8086fb16fc12d5d64536780e1da7405a800b0b9f6);
uint256 constant BulkOrder_Typehash_Height_Six =
(0x1c19f71958cdd8f081b4c31f7caf5c010b29d12950be2fa1c95070dc47e30b55);
uint256 constant BulkOrder_Typehash_Height_Seven =
(0xca74fab2fece9a1d58234a274220ad05ca096a92ef6a1ca1750b9d90c948955c);
uint256 constant BulkOrder_Typehash_Height_Eight =
(0x7ff98d9d4e55d876c5cfac10b43c04039522f3ddfb0ea9bfe70c68cfb5c7cc14);
uint256 constant BulkOrder_Typehash_Height_Nine =
(0xbed7be92d41c56f9e59ac7a6272185299b815ddfabc3f25deb51fe55fe2f9e8a);
uint256 constant BulkOrder_Typehash_Height_Ten =
(0xd1d97d1ef5eaa37a4ee5fbf234e6f6d64eb511eb562221cd7edfbdde0848da05);
uint256 constant BulkOrder_Typehash_Height_Eleven =
(0x896c3f349c4da741c19b37fec49ed2e44d738e775a21d9c9860a69d67a3dae53);
uint256 constant BulkOrder_Typehash_Height_Twelve =
(0xbb98d87cc12922b83759626c5f07d72266da9702d19ffad6a514c73a89002f5f);
uint256 constant BulkOrder_Typehash_Height_Thirteen =
(0xe6ae19322608dd1f8a8d56aab48ed9c28be489b689f4b6c91268563efc85f20e);
uint256 constant BulkOrder_Typehash_Height_Fourteen =
(0x6b5b04cbae4fcb1a9d78e7b2dfc51a36933d023cf6e347e03d517b472a852590);
uint256 constant BulkOrder_Typehash_Height_Fifteen =
(0xd1eb68309202b7106b891e109739dbbd334a1817fe5d6202c939e75cf5e35ca9);
uint256 constant BulkOrder_Typehash_Height_Sixteen =
(0x1da3eed3ecef6ebaa6e5023c057ec2c75150693fd0dac5c90f4a142f9879fde8);
uint256 constant BulkOrder_Typehash_Height_Seventeen =
(0xeee9a1392aa395c7002308119a58f2582777a75e54e0c1d5d5437bd2e8bf6222);
uint256 constant BulkOrder_Typehash_Height_Eighteen =
(0xc3939feff011e53ab8c35ca3370aad54c5df1fc2938cd62543174fa6e7d85877);
uint256 constant BulkOrder_Typehash_Height_Nineteen =
(0x0efca7572ac20f5ae84db0e2940674f7eca0a4726fa1060ffc2d18cef54b203d);
uint256 constant BulkOrder_Typehash_Height_Twenty =
(0x5a4f867d3d458dabecad65f6201ceeaba0096df2d0c491cc32e6ea4e64350017);
uint256 constant BulkOrder_Typehash_Height_TwentyOne =
(0x80987079d291feebf21c2230e69add0f283cee0b8be492ca8050b4185a2ff719);
uint256 constant BulkOrder_Typehash_Height_TwentyTwo =
(0x3bd8cff538aba49a9c374c806d277181e9651624b3e31111bc0624574f8bca1d);
uint256 constant BulkOrder_Typehash_Height_TwentyThree =
(0x5d6a3f098a0bc373f808c619b1bb4028208721b3c4f8d6bc8a874d659814eb76);
uint256 constant BulkOrder_Typehash_Height_TwentyFour =
(0x1d51df90cba8de7637ca3e8fe1e3511d1dc2f23487d05dbdecb781860c21ac1c);
uint256 constant receivedItemsHash_ptr = 0x60;
/*
* Memory layout in _prepareBasicFulfillmentFromCalldata of
* data for OrderFulfilled
*
* event OrderFulfilled(
* bytes32 orderHash,
* address indexed offerer,
* address indexed zone,
* address fulfiller,
* SpentItem[] offer,
* > (itemType, token, id, amount)
* ReceivedItem[] consideration
* > (itemType, token, id, amount, recipient)
* )
*
* - 0x00: orderHash
* - 0x20: fulfiller
* - 0x40: offer offset (0x80)
* - 0x60: consideration offset (0x120)
* - 0x80: offer.length (1)
* - 0xa0: offerItemType
* - 0xc0: offerToken
* - 0xe0: offerIdentifier
* - 0x100: offerAmount
* - 0x120: consideration.length (1 + additionalRecipients.length)
* - 0x140: considerationItemType
* - 0x160: considerationToken
* - 0x180: considerationIdentifier
* - 0x1a0: considerationAmount
* - 0x1c0: considerationRecipient
* - ...
*/
// Minimum length of the OrderFulfilled event data.
// Must be added to the size of the ReceivedItem array for additionalRecipients
// (0xa0 * additionalRecipients.length) to calculate full size of the buffer.
uint256 constant OrderFulfilled_baseSize = 0x1e0;
uint256 constant OrderFulfilled_selector =
(0x9d9af8e38d66c62e2c12f0225249fd9d721c54b83f48d9352c97c6cacdcb6f31);
// Minimum offset in memory to OrderFulfilled event data.
// Must be added to the size of the EIP712 hash array for additionalRecipients
// (32 * additionalRecipients.length) to calculate the pointer to event data.
uint256 constant OrderFulfilled_baseOffset = 0x180;
uint256 constant OrderFulfilled_consideration_length_baseOffset = 0x2a0;
uint256 constant OrderFulfilled_offer_length_baseOffset = 0x200;
uint256 constant OrderFulfilled_offer_length_offset_relativeTo_baseOffset = (
0x80
);
uint256 constant OrderFulfilled_offer_itemType_offset_relativeTo_baseOffset = (
0xa0
);
uint256 constant OrderFulfilled_offer_token_offset_relativeTo_baseOffset = 0xc0;
// Related constants used for restricted order checks on basic orders.
uint256 constant OrderFulfilled_baseDataSize = 0x160;
// uint256 constant ValidateOrder_offerDataOffset = 0x184;
// uint256 constant RatifyOrder_offerDataOffset = 0xc4;
// uint256 constant OrderFulfilled_orderHash_offset = 0x00;
uint256 constant OrderFulfilled_fulfiller_offset = 0x20;
uint256 constant OrderFulfilled_offer_head_offset = 0x40;
uint256 constant OrderFulfilled_offer_body_offset = 0x80;
uint256 constant OrderFulfilled_consideration_head_offset = 0x60;
uint256 constant OrderFulfilled_consideration_body_offset = 0x120;
/*
* 3 memory slots/words for `authorizeOrder` and `validateOrder` calldata
* to be used for tails of extra data (length 0) and order hashes (length 1)
*/
uint256 constant OrderFulfilled_post_memory_region_reservedBytes = 0x60;
/*
* OrderFulfilled_offer_length_baseOffset - 12 * 0x20
* we back up 12 words from where the `OrderFulfilled`'s data
* for spent items start to be rewritten for `authorizeOrder`
* and `validateOrder`. Let the reference pointer be `ptr`
* pointing to the `OrderFulfilled`'s spent item array's length memory
* position then we would have:
*
* ptr - 0x0180 : zero-padded calldata selector
* ptr - 0x0160 : ZoneParameter's struct head (0x20)
* ptr - 0x0140 : order hash
* ptr - 0x0120 : fulfiller (msg.sender)
* ptr - 0x0100 : offerer
* ptr - 0x00e0 : spent items' head
* ptr - 0x00c0 : received items' head
* ptr - 0x00a0 : extra data / context head
* ptr - 0x0080 : order hashes head
* ptr - 0x0060 : start time
* ptr - 0x0040 : end time
* ptr - 0x0020 : zone hash
* ptr - 0x0000 : offer.length (1)
* ...
*
* Note that the padded calldata selector will be at minimum at the
* 0x80 memory slot.
*/
uint256 constant authorizeOrder_calldata_baseOffset = (
OrderFulfilled_offer_length_baseOffset - 0x180
);
// BasicOrderParameters
uint256 constant BasicOrder_parameters_cdPtr = 0x04;
uint256 constant BasicOrder_considerationToken_cdPtr = 0x24;
uint256 constant BasicOrder_considerationIdentifier_cdPtr = 0x44;
uint256 constant BasicOrder_considerationAmount_cdPtr = 0x64;
uint256 constant BasicOrder_offerer_cdPtr = 0x84;
uint256 constant BasicOrder_zone_cdPtr = 0xa4;
uint256 constant BasicOrder_offerToken_cdPtr = 0xc4;
uint256 constant BasicOrder_offerIdentifier_cdPtr = 0xe4;
uint256 constant BasicOrder_offerAmount_cdPtr = 0x104;
uint256 constant BasicOrder_basicOrderParameters_cd_offset = 0x24;
uint256 constant BasicOrder_basicOrderType_cdPtr = 0x124;
uint256 constant BasicOrder_startTime_cdPtr = 0x144;
uint256 constant BasicOrder_endTime_cdPtr = 0x164;
// uint256 constant BasicOrder_zoneHash_cdPtr = 0x184;
// uint256 constant BasicOrder_salt_cdPtr = 0x1a4;
uint256 constant BasicOrder_offererConduit_cdPtr = 0x1c4;
uint256 constant BasicOrder_fulfillerConduit_cdPtr = 0x1e4;
uint256 constant BasicOrder_totalOriginalAdditionalRecipients_cdPtr = 0x204;
uint256 constant BasicOrder_additionalRecipients_head_cdPtr = 0x224;
uint256 constant BasicOrder_signature_cdPtr = 0x244;
uint256 constant BasicOrder_additionalRecipients_length_cdPtr = 0x264;
uint256 constant BasicOrder_addlRecipients_length_cdPtr = 0x264;
uint256 constant BasicOrder_additionalRecipients_data_cdPtr = 0x284;
uint256 constant BasicOrder_parameters_ptr = 0x20;
uint256 constant BasicOrder_basicOrderType_range = 0x18; // 24 values
/*
* Memory layout in _prepareBasicFulfillmentFromCalldata of
* EIP712 data for ConsiderationItem
* - 0x80: ConsiderationItem EIP-712 typehash (constant)
* - 0xa0: itemType
* - 0xc0: token
* - 0xe0: identifier
* - 0x100: startAmount
* - 0x120: endAmount
* - 0x140: recipient
*/
uint256 constant BasicOrder_considerationItem_typeHash_ptr = 0x80; // memoryPtr
uint256 constant BasicOrder_considerationItem_itemType_ptr = 0xa0;
uint256 constant BasicOrder_considerationItem_token_ptr = 0xc0;
uint256 constant BasicOrder_considerationItem_identifier_ptr = 0xe0;
uint256 constant BasicOrder_considerationItem_startAmount_ptr = 0x100;
uint256 constant BasicOrder_considerationItem_endAmount_ptr = 0x120;
// uint256 constant BasicOrder_considerationItem_recipient_ptr = 0x140;
/*
* Memory layout in _prepareBasicFulfillmentFromCalldata of
* EIP712 data for OfferItem
* - 0x80: OfferItem EIP-712 typehash (constant)
* - 0xa0: itemType
* - 0xc0: token
* - 0xe0: identifier (reused for offeredItemsHash)
* - 0x100: startAmount
* - 0x120: endAmount
*/
uint256 constant BasicOrder_offerItem_typeHash_ptr = 0x80;
uint256 constant BasicOrder_offerItem_itemType_ptr = 0xa0;
uint256 constant BasicOrder_offerItem_token_ptr = 0xc0;
// uint256 constant BasicOrder_offerItem_identifier_ptr = 0xe0;
// uint256 constant BasicOrder_offerItem_startAmount_ptr = 0x100;
uint256 constant BasicOrder_offerItem_endAmount_ptr = 0x120;
/*
* Memory layout in _prepareBasicFulfillmentFromCalldata of
* EIP712 data for Order
* - 0x80: Order EIP-712 typehash (constant)
* - 0xa0: orderParameters.offerer
* - 0xc0: orderParameters.zone
* - 0xe0: keccak256(abi.encodePacked(offerHashes))
* - 0x100: keccak256(abi.encodePacked(considerationHashes))
* - 0x120: orderType
* - 0x140: startTime
* - 0x160: endTime
* - 0x180: zoneHash
* - 0x1a0: salt
* - 0x1c0: conduit
* - 0x1e0: _counters[orderParameters.offerer] (from storage)
*/
uint256 constant BasicOrder_order_typeHash_ptr = 0x80;
uint256 constant BasicOrder_order_offerer_ptr = 0xa0;
// uint256 constant BasicOrder_order_zone_ptr = 0xc0;
uint256 constant BasicOrder_order_offerHashes_ptr = 0xe0;
uint256 constant BasicOrder_order_considerationHashes_ptr = 0x100;
uint256 constant BasicOrder_order_orderType_ptr = 0x120;
uint256 constant BasicOrder_order_startTime_ptr = 0x140;
// uint256 constant BasicOrder_order_endTime_ptr = 0x160;
// uint256 constant BasicOrder_order_zoneHash_ptr = 0x180;
// uint256 constant BasicOrder_order_salt_ptr = 0x1a0;
// uint256 constant BasicOrder_order_conduitKey_ptr = 0x1c0;
uint256 constant BasicOrder_order_counter_ptr = 0x1e0;
uint256 constant BasicOrder_additionalRecipients_head_ptr = 0x240;
uint256 constant BasicOrder_signature_ptr = 0x260;
uint256 constant BasicOrder_startTimeThroughZoneHash_size = 0x60;
uint256 constant ContractOrder_orderHash_offerer_shift = 0x60;
uint256 constant Counter_blockhash_shift = 0x80;
// Signature-related
bytes32 constant EIP2098_allButHighestBitMask =
(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
bytes32 constant ECDSA_twentySeventhAndTwentyEighthBytesSet =
(0x0000000000000000000000000000000000000000000000000000000101000000);
uint256 constant ECDSA_MaxLength = 65;
uint256 constant ECDSA_signature_s_offset = 0x40;
uint256 constant ECDSA_signature_v_offset = 0x60;
bytes32 constant EIP1271_isValidSignature_selector =
(0x1626ba7e00000000000000000000000000000000000000000000000000000000);
uint256 constant EIP1271_isValidSignature_digest_negativeOffset = 0x40;
uint256 constant EIP1271_isValidSignature_selector_negativeOffset = 0x44;
uint256 constant EIP1271_isValidSignature_calldata_baseLength = 0x64;
uint256 constant EIP1271_isValidSignature_signature_head_offset = 0x40;
uint256 constant EIP_712_PREFIX =
(0x1901000000000000000000000000000000000000000000000000000000000000);
uint256 constant ExtraGasBuffer = 0x20;
uint256 constant CostPerWord = 0x3;
uint256 constant MemoryExpansionCoefficientShift = 0x9;
uint256 constant Create2AddressDerivation_ptr = 0x0b;
uint256 constant Create2AddressDerivation_length = 0x55;
uint256 constant MaskOverByteTwelve =
(0x0000000000000000000000ff0000000000000000000000000000000000000000);
uint256 constant MaskOverLastTwentyBytes =
(0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff);
uint256 constant AddressDirtyUpperBitThreshold =
(0x0000000000000000000000010000000000000000000000000000000000000000);
uint256 constant MaskOverFirstFourBytes =
(0xffffffff00000000000000000000000000000000000000000000000000000000);
uint256 constant Conduit_execute_signature =
(0x4ce34aa200000000000000000000000000000000000000000000000000000000);
uint256 constant MaxUint8 = 0xff;
uint256 constant MaxUint120 = 0xffffffffffffffffffffffffffffff;
uint256 constant Conduit_execute_ConduitTransfer_ptr = 0x20;
uint256 constant Conduit_execute_ConduitTransfer_length = 0x01;
uint256 constant Conduit_execute_ConduitTransfer_offset_ptr = 0x04;
uint256 constant Conduit_execute_ConduitTransfer_length_ptr = 0x24;
uint256 constant Conduit_execute_transferItemType_ptr = 0x44;
uint256 constant Conduit_execute_transferToken_ptr = 0x64;
uint256 constant Conduit_execute_transferFrom_ptr = 0x84;
uint256 constant Conduit_execute_transferTo_ptr = 0xa4;
uint256 constant Conduit_execute_transferIdentifier_ptr = 0xc4;
uint256 constant Conduit_execute_transferAmount_ptr = 0xe4;
uint256 constant OneConduitExecute_size = 0x104;
// Sentinel value to indicate that the conduit accumulator is not armed.
uint256 constant AccumulatorDisarmed = 0x20;
uint256 constant AccumulatorArmed = 0x40;
uint256 constant Accumulator_conduitKey_ptr = 0x20;
uint256 constant Accumulator_selector_ptr = 0x40;
uint256 constant Accumulator_array_offset_ptr = 0x44;
uint256 constant Accumulator_array_length_ptr = 0x64;
uint256 constant Accumulator_itemSizeOffsetDifference = 0x3c;
uint256 constant Accumulator_array_offset = 0x20;
uint256 constant Conduit_transferItem_size = 0xc0;
uint256 constant Conduit_transferItem_token_ptr = 0x20;
uint256 constant Conduit_transferItem_from_ptr = 0x40;
uint256 constant Conduit_transferItem_to_ptr = 0x60;
uint256 constant Conduit_transferItem_identifier_ptr = 0x80;
uint256 constant Conduit_transferItem_amount_ptr = 0xa0;
uint256 constant Ecrecover_precompile = 0x1;
uint256 constant Ecrecover_args_size = 0x80;
uint256 constant Signature_lower_v = 27;
// Bitmask that only gives a non-zero value if masked with a non-match selector.
uint256 constant NonMatchSelector_MagicMask =
(0x4000000000000000000000000000000000000000000000000000000000);
// First bit indicates that a NATIVE offer items has been used and the 231st bit
// indicates that a non match selector has been called.
uint256 constant NonMatchSelector_InvalidErrorValue =
(0x4000000000000000000000000000000000000000000000000000000001);
/**
* @dev Selector and offsets for generateOrder
*
* function generateOrder(
* address fulfiller,
* SpentItem[] calldata minimumReceived,
* SpentItem[] calldata maximumSpent,
* bytes calldata context
* )
*/
uint256 constant generateOrder_selector = 0x98919765;
uint256 constant generateOrder_selector_offset = 0x1c;
uint256 constant generateOrder_head_offset = 0x04;
uint256 constant generateOrder_minimumReceived_head_offset = 0x20;
uint256 constant generateOrder_maximumSpent_head_offset = 0x40;
uint256 constant generateOrder_context_head_offset = 0x60;
uint256 constant generateOrder_base_tail_offset = 0x80;
uint256 constant generateOrder_maximum_returned_array_length = 0xffff;
uint256 constant ratifyOrder_selector = 0xf4dd92ce;
uint256 constant ratifyOrder_selector_offset = 0x1c;
uint256 constant ratifyOrder_head_offset = 0x04;
// uint256 constant ratifyOrder_offer_head_offset = 0x00;
uint256 constant ratifyOrder_consideration_head_offset = 0x20;
uint256 constant ratifyOrder_context_head_offset = 0x40;
uint256 constant ratifyOrder_orderHashes_head_offset = 0x60;
uint256 constant ratifyOrder_contractNonce_offset = 0x80;
uint256 constant ratifyOrder_base_tail_offset = 0xa0;
uint256 constant validateOrder_selector = 0x17b1f942;
uint256 constant validateOrder_selector_offset = 0x1c;
uint256 constant validateOrder_head_offset = 0x04;
uint256 constant validateOrder_zoneParameters_offset = 0x20;
uint256 constant authorizeOrder_selector = 0x01e4d72a;
uint256 constant authorizeOrder_selector_offset = 0x1c;
uint256 constant authorizeOrder_head_offset = 0x04;
uint256 constant authorizeOrder_zoneParameters_offset = 0x20;
// uint256 constant ZoneParameters_orderHash_offset = 0x00;
uint256 constant ZoneParameters_fulfiller_offset = 0x20;
uint256 constant ZoneParameters_offerer_offset = 0x40;
uint256 constant ZoneParameters_offer_head_offset = 0x60;
uint256 constant ZoneParameters_consideration_head_offset = 0x80;
uint256 constant ZoneParameters_extraData_head_offset = 0xa0;
uint256 constant ZoneParameters_orderHashes_head_offset = 0xc0;
uint256 constant ZoneParameters_startTime_offset = 0xe0;
uint256 constant ZoneParameters_endTime_offset = 0x100;
uint256 constant ZoneParameters_zoneHash_offset = 0x120;
uint256 constant ZoneParameters_base_tail_offset = 0x140;
uint256 constant ZoneParameters_selectorAndPointer_length = 0x24;
uint256 constant ZoneParameters_basicOrderFixedElements_length = 0x44;
// ConsiderationDecoder Constants
uint256 constant OrderParameters_head_size = 0x0160;
uint256 constant OrderParameters_totalOriginalConsiderationItems_offset = (
0x0140
);
uint256 constant AdvancedOrderPlusOrderParameters_head_size = 0x0200;
uint256 constant Order_signature_offset = 0x20;
uint256 constant Order_head_size = 0x40;
uint256 constant AdvancedOrder_fixed_segment_0 = 0x40;
uint256 constant CriteriaResolver_head_size = 0xa0;
uint256 constant CriteriaResolver_fixed_segment_0 = 0x80;
uint256 constant CriteriaResolver_criteriaProof_offset = 0x80;
uint256 constant FulfillmentComponent_mem_tail_size = 0x40;
uint256 constant FulfillmentComponent_mem_tail_size_shift = 0x6;
uint256 constant Fulfillment_head_size = 0x40;
uint256 constant Fulfillment_considerationComponents_offset = 0x20;
uint256 constant OrderComponents_OrderParameters_common_head_size = 0x0140;
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
ConsiderationEventsAndErrors
} from "seaport-types/src/interfaces/ConsiderationEventsAndErrors.sol";
import {
ReentrancyErrors
} from "seaport-types/src/interfaces/ReentrancyErrors.sol";
import {
_ENTERED_AND_ACCEPTING_NATIVE_TOKENS_SSTORE,
_ENTERED_SSTORE,
_NOT_ENTERED_SSTORE
} from "seaport-types/src/lib/ConsiderationConstants.sol";
/**
* @title ReentrancyGuard
* @author 0age
* @notice ReentrancyGuard contains a storage variable and related functionality
* for protecting against reentrancy.
*/
contract ReferenceReentrancyGuard is
ConsiderationEventsAndErrors,
ReentrancyErrors
{
// Prevent reentrant calls on protected functions.
uint256 private _reentrancyGuard;
/**
* @dev Initialize the reentrancy guard during deployment.
*/
constructor() {
// Initialize the reentrancy guard in a cleared state.
_reentrancyGuard = _NOT_ENTERED_SSTORE;
}
/**
* @dev Modifier to check that the sentinel value for the reentrancy guard
* is not currently set by a previous call.
*/
modifier notEntered() {
if (_reentrancyGuard != _NOT_ENTERED_SSTORE) {
revert NoReentrantCalls();
}
_;
}
/**
* @dev Modifier to set the reentrancy guard sentinel value for the duration
* of the call and check if it is already set by a previous call.
*
* @param acceptNativeTokens A boolean indicating whether native tokens may
* be received during execution or not.
*/
modifier nonReentrant(bool acceptNativeTokens) {
if (_reentrancyGuard != _NOT_ENTERED_SSTORE) {
revert NoReentrantCalls();
}
if (acceptNativeTokens) {
_reentrancyGuard = _ENTERED_AND_ACCEPTING_NATIVE_TOKENS_SSTORE;
} else {
_reentrancyGuard = _ENTERED_SSTORE;
}
_;
_reentrancyGuard = _NOT_ENTERED_SSTORE;
}
/**
* @dev Internal view function to ensure that the sentinel value indicating
* native tokens may be received during execution is currently set.
*/
function _assertAcceptingNativeTokens() internal view {
// Ensure that the reentrancy guard is not currently set.
if (_reentrancyGuard != _ENTERED_AND_ACCEPTING_NATIVE_TOKENS_SSTORE) {
revert InvalidMsgValue(msg.value);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {ConduitControllerInterface} from "seaport-types/src/interfaces/ConduitControllerInterface.sol";
import {ConsiderationEventsAndErrors} from "seaport-types/src/interfaces/ConsiderationEventsAndErrors.sol";
import {ReentrancyErrors} from "seaport-types/src/interfaces/ReentrancyErrors.sol";
/**
* @title ConsiderationBase
* @author 0age
* @notice ConsiderationBase contains all storage, constants, and constructor
* logic.
*/
contract ReferenceConsiderationBase is
ConsiderationEventsAndErrors,
ReentrancyErrors
{
// Declare constants for name, version, and reentrancy sentinel values.
string internal constant _NAME = "Seaport";
string internal constant _VERSION = "1.6";
uint256 internal constant _NOT_ENTERED = 1;
uint256 internal constant _ENTERED = 2;
// Precompute hashes, original chainId, and domain separator on deployment.
bytes32 internal immutable _NAME_HASH;
bytes32 internal immutable _VERSION_HASH;
bytes32 internal immutable _EIP_712_DOMAIN_TYPEHASH;
bytes32 internal immutable _OFFER_ITEM_TYPEHASH;
bytes32 internal immutable _CONSIDERATION_ITEM_TYPEHASH;
bytes32 internal immutable _ORDER_TYPEHASH;
bytes32 internal immutable _BULK_ORDER_TYPEHASH;
uint256 internal immutable _CHAIN_ID;
bytes32 internal immutable _DOMAIN_SEPARATOR;
// Allow for interaction with the conduit controller.
ConduitControllerInterface internal immutable _CONDUIT_CONTROLLER;
// Cache the conduit code hashes used by the conduit controller.
bytes32 internal immutable _CONDUIT_CREATION_CODE_HASH;
bytes32 internal immutable _CONDUIT_RUNTIME_CODE_HASH;
// Map bulk order tree height to its respective EIP-712 typehash.
mapping(uint256 => bytes32) internal _bulkOrderTypehashes;
/**
* @dev Derive and set hashes, reference chainId, and associated domain
* separator during deployment.
*
* @param conduitController A contract that deploys conduits, or
* proxies that may optionally be used to
* transfer approved ERC20+721+1155
* tokens.
*/
constructor(address conduitController) {
// Derive name and version hashes alongside required EIP-712 typehashes.
(
_NAME_HASH,
_VERSION_HASH,
_EIP_712_DOMAIN_TYPEHASH,
_OFFER_ITEM_TYPEHASH,
_CONSIDERATION_ITEM_TYPEHASH,
_ORDER_TYPEHASH,
_BULK_ORDER_TYPEHASH,
_DOMAIN_SEPARATOR
) = _deriveTypehashes();
// Store the current chainId and derive the current domain separator.
_CHAIN_ID = block.chainid;
// Set supplied conduit controller to an in-memory controller interface.
ConduitControllerInterface tempController = ConduitControllerInterface(
conduitController
);
// Assign the in-memory interface as an immutable.
_CONDUIT_CONTROLLER = tempController;
// Retrieve the conduit creation code hash from the supplied controller.
(_CONDUIT_CREATION_CODE_HASH, _CONDUIT_RUNTIME_CODE_HASH) = (
tempController.getConduitCodeHashes()
);
_bulkOrderTypehashes[1] = bytes32(
0x3ca2711d29384747a8f61d60aad3c450405f7aaff5613541dee28df2d6986d32
);
_bulkOrderTypehashes[2] = bytes32(
0xbf8e29b89f29ed9b529c154a63038ffca562f8d7cd1e2545dda53a1b582dde30
);
_bulkOrderTypehashes[3] = bytes32(
0x53c6f6856e13104584dd0797ca2b2779202dc2597c6066a42e0d8fe990b0024d
);
_bulkOrderTypehashes[4] = bytes32(
0xa02eb7ff164c884e5e2c336dc85f81c6a93329d8e9adf214b32729b894de2af1
);
_bulkOrderTypehashes[5] = bytes32(
0x39c9d33c18e050dda0aeb9a8086fb16fc12d5d64536780e1da7405a800b0b9f6
);
_bulkOrderTypehashes[6] = bytes32(
0x1c19f71958cdd8f081b4c31f7caf5c010b29d12950be2fa1c95070dc47e30b55
);
_bulkOrderTypehashes[7] = bytes32(
0xca74fab2fece9a1d58234a274220ad05ca096a92ef6a1ca1750b9d90c948955c
);
_bulkOrderTypehashes[8] = bytes32(
0x7ff98d9d4e55d876c5cfac10b43c04039522f3ddfb0ea9bfe70c68cfb5c7cc14
);
_bulkOrderTypehashes[9] = bytes32(
0xbed7be92d41c56f9e59ac7a6272185299b815ddfabc3f25deb51fe55fe2f9e8a
);
_bulkOrderTypehashes[10] = bytes32(
0xd1d97d1ef5eaa37a4ee5fbf234e6f6d64eb511eb562221cd7edfbdde0848da05
);
_bulkOrderTypehashes[11] = bytes32(
0x896c3f349c4da741c19b37fec49ed2e44d738e775a21d9c9860a69d67a3dae53
);
_bulkOrderTypehashes[12] = bytes32(
0xbb98d87cc12922b83759626c5f07d72266da9702d19ffad6a514c73a89002f5f
);
_bulkOrderTypehashes[13] = bytes32(
0xe6ae19322608dd1f8a8d56aab48ed9c28be489b689f4b6c91268563efc85f20e
);
_bulkOrderTypehashes[14] = bytes32(
0x6b5b04cbae4fcb1a9d78e7b2dfc51a36933d023cf6e347e03d517b472a852590
);
_bulkOrderTypehashes[15] = bytes32(
0xd1eb68309202b7106b891e109739dbbd334a1817fe5d6202c939e75cf5e35ca9
);
_bulkOrderTypehashes[16] = bytes32(
0x1da3eed3ecef6ebaa6e5023c057ec2c75150693fd0dac5c90f4a142f9879fde8
);
_bulkOrderTypehashes[17] = bytes32(
0xeee9a1392aa395c7002308119a58f2582777a75e54e0c1d5d5437bd2e8bf6222
);
_bulkOrderTypehashes[18] = bytes32(
0xc3939feff011e53ab8c35ca3370aad54c5df1fc2938cd62543174fa6e7d85877
);
_bulkOrderTypehashes[19] = bytes32(
0x0efca7572ac20f5ae84db0e2940674f7eca0a4726fa1060ffc2d18cef54b203d
);
_bulkOrderTypehashes[20] = bytes32(
0x5a4f867d3d458dabecad65f6201ceeaba0096df2d0c491cc32e6ea4e64350017
);
_bulkOrderTypehashes[21] = bytes32(
0x80987079d291feebf21c2230e69add0f283cee0b8be492ca8050b4185a2ff719
);
_bulkOrderTypehashes[22] = bytes32(
0x3bd8cff538aba49a9c374c806d277181e9651624b3e31111bc0624574f8bca1d
);
_bulkOrderTypehashes[23] = bytes32(
0x5d6a3f098a0bc373f808c619b1bb4028208721b3c4f8d6bc8a874d659814eb76
);
_bulkOrderTypehashes[24] = bytes32(
0x1d51df90cba8de7637ca3e8fe1e3511d1dc2f23487d05dbdecb781860c21ac1c
);
}
/**
* @dev Internal view function to derive the initial EIP-712 domain
* separator.
*
* @param _eip712DomainTypeHash The primary EIP-712 domain typehash.
* @param _nameHash The hash of the name of the contract.
* @param _versionHash The hash of the version string of the
* contract.
*
* @return domainSeparator The derived domain separator.
*/
function _deriveInitialDomainSeparator(
bytes32 _eip712DomainTypeHash,
bytes32 _nameHash,
bytes32 _versionHash
) internal view virtual returns (bytes32 domainSeparator) {
return
_deriveDomainSeparator(
_eip712DomainTypeHash,
_nameHash,
_versionHash
);
}
/**
* @dev Internal view function to derive the EIP-712 domain separator.
*
* @return The derived domain separator.
*/
function _deriveDomainSeparator(
bytes32 _eip712DomainTypeHash,
bytes32 _nameHash,
bytes32 _versionHash
) internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
_eip712DomainTypeHash,
_nameHash,
_versionHash,
block.chainid,
address(this)
)
);
}
/**
* @dev Internal pure function to derive required EIP-712 typehashes and
* other hashes during contract creation.
*
* @return nameHash The hash of the name of the contract.
* @return versionHash The hash of the version string of the
* contract.
* @return eip712DomainTypehash The primary EIP-712 domain typehash.
* @return offerItemTypehash The EIP-712 typehash for OfferItem
* types.
* @return considerationItemTypehash The EIP-712 typehash for
* ConsiderationItem types.
* @return orderTypehash The EIP-712 typehash for Order types.
* @return bulkOrderTypeHash
* @return domainSeparator The domain separator.
*/
function _deriveTypehashes()
internal
view
returns (
bytes32 nameHash,
bytes32 versionHash,
bytes32 eip712DomainTypehash,
bytes32 offerItemTypehash,
bytes32 considerationItemTypehash,
bytes32 orderTypehash,
bytes32 bulkOrderTypeHash,
bytes32 domainSeparator
)
{
// Derive hash of the name of the contract.
nameHash = keccak256(bytes(_NAME));
// Derive hash of the version string of the contract.
versionHash = keccak256(bytes(_VERSION));
// Construct the OfferItem type string.
bytes memory offerItemTypeString = abi.encodePacked(
"OfferItem(",
"uint8 itemType,",
"address token,",
"uint256 identifierOrCriteria,",
"uint256 startAmount,",
"uint256 endAmount",
")"
);
// Construct the ConsiderationItem type string.
bytes memory considerationItemTypeString = abi.encodePacked(
"ConsiderationItem(",
"uint8 itemType,",
"address token,",
"uint256 identifierOrCriteria,",
"uint256 startAmount,",
"uint256 endAmount,",
"address recipient",
")"
);
// Construct the OrderComponents type string, not including the above.
bytes memory orderComponentsPartialTypeString = abi.encodePacked(
"OrderComponents(",
"address offerer,",
"address zone,",
"OfferItem[] offer,",
"ConsiderationItem[] consideration,",
"uint8 orderType,",
"uint256 startTime,",
"uint256 endTime,",
"bytes32 zoneHash,",
"uint256 salt,",
"bytes32 conduitKey,",
"uint256 counter",
")"
);
// Construct the primary EIP-712 domain type string.
eip712DomainTypehash = keccak256(
abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"uint256 chainId,",
"address verifyingContract",
")"
)
);
// Derive the OfferItem type hash using the corresponding type string.
offerItemTypehash = keccak256(offerItemTypeString);
// Derive ConsiderationItem type hash using corresponding type string.
considerationItemTypehash = keccak256(considerationItemTypeString);
// Derive OrderItem type hash via combination of relevant type strings.
orderTypehash = keccak256(
abi.encodePacked(
orderComponentsPartialTypeString,
considerationItemTypeString,
offerItemTypeString
)
);
// Encode the type string for the BulkOrder struct.
bytes memory bulkOrderPartialTypeString = abi.encodePacked(
"BulkOrder(OrderComponents[2][2][2][2][2][2][2] tree)"
);
// Generate the keccak256 hash of the concatenated type strings for the
// BulkOrder, considerationItem, offerItem, and orderComponents.
bulkOrderTypeHash = keccak256(
abi.encodePacked(
bulkOrderPartialTypeString,
considerationItemTypeString,
offerItemTypeString,
orderComponentsPartialTypeString
)
);
// Derive the initial domain separator using the domain typehash, the
// name hash, and the version hash.
domainSeparator = _deriveInitialDomainSeparator(
eip712DomainTypehash,
nameHash,
versionHash
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @title ReentrancyErrors
* @author 0age
* @notice ReentrancyErrors contains errors related to reentrancy.
*/
interface ReentrancyErrors {
/**
* @dev Revert with an error when a caller attempts to reenter a protected
* function.
*/
error NoReentrantCalls();
/**
* @dev Revert with an error when attempting to activate the TSTORE opcode
* when it is already active.
*/
error TStoreAlreadyActivated();
/**
* @dev Revert with an error when attempting to activate the TSTORE opcode
* in an EVM environment that does not support it.
*/
error TStoreNotSupported();
/**
* @dev Revert with an error when deployment of the contract for testing
* TSTORE support fails.
*/
error TloadTestContractDeploymentFailed();
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import {
OrderParameters,
ReceivedItem,
SpentItem
} from "../lib/ConsiderationStructs.sol";
/**
* @title ConsiderationEventsAndErrors
* @author 0age
* @notice ConsiderationEventsAndErrors contains all events and errors.
*/
interface ConsiderationEventsAndErrors {
/**
* @dev Emit an event whenever an order is successfully fulfilled.
*
* @param orderHash The hash of the fulfilled order.
* @param offerer The offerer of the fulfilled order.
* @param zone The zone of the fulfilled order.
* @param recipient The recipient of each spent item on the fulfilled
* order, or the null address if there is no specific
* fulfiller (i.e. the order is part of a group of
* orders). Defaults to the caller unless explicitly
* specified otherwise by the fulfiller.
* @param offer The offer items spent as part of the order.
* @param consideration The consideration items received as part of the
* order along with the recipients of each item.
*/
event OrderFulfilled(
bytes32 orderHash,
address indexed offerer,
address indexed zone,
address recipient,
SpentItem[] offer,
ReceivedItem[] consideration
);
/**
* @dev Emit an event whenever an order is successfully cancelled.
*
* @param orderHash The hash of the cancelled order.
* @param offerer The offerer of the cancelled order.
* @param zone The zone of the cancelled order.
*/
event OrderCancelled(
bytes32 orderHash,
address indexed offerer,
address indexed zone
);
/**
* @dev Emit an event whenever an order is explicitly validated. Note that
* this event will not be emitted on partial fills even though they do
* validate the order as part of partial fulfillment.
*
* @param orderHash The hash of the validated order.
* @param orderParameters The parameters of the validated order.
*/
event OrderValidated(bytes32 orderHash, OrderParameters orderParameters);
/**
* @dev Emit an event whenever one or more orders are matched using either
* matchOrders or matchAdvancedOrders.
*
* @param orderHashes The order hashes of the matched orders.
*/
event OrdersMatched(bytes32[] orderHashes);
/**
* @dev Emit an event whenever a counter for a given offerer is incremented.
*
* @param newCounter The new counter for the offerer.
* @param offerer The offerer in question.
*/
event CounterIncremented(uint256 newCounter, address indexed offerer);
/**
* @dev Revert with an error when attempting to fill an order that has
* already been fully filled.
*
* @param orderHash The order hash on which a fill was attempted.
*/
error OrderAlreadyFilled(bytes32 orderHash);
/**
* @dev Revert with an error when attempting to fill an order outside the
* specified start time and end time.
*
* @param startTime The time at which the order becomes active.
* @param endTime The time at which the order becomes inactive.
*/
error InvalidTime(uint256 startTime, uint256 endTime);
/**
* @dev Revert with an error when attempting to fill an order referencing an
* invalid conduit (i.e. one that has not been deployed).
*/
error InvalidConduit(bytes32 conduitKey, address conduit);
/**
* @dev Revert with an error when an order is supplied for fulfillment with
* a consideration array that is shorter than the original array.
*/
error MissingOriginalConsiderationItems();
/**
* @dev Revert with an error when an order is validated and the length of
* the consideration array is not equal to the supplied total original
* consideration items value. This error is also thrown when contract
* orders supply a total original consideration items value that does
* not match the supplied consideration array length.
*/
error ConsiderationLengthNotEqualToTotalOriginal();
/**
* @dev Revert with an error when a call to a conduit fails with revert data
* that is too expensive to return.
*/
error InvalidCallToConduit(address conduit);
/**
* @dev Revert with an error if a consideration amount has not been fully
* zeroed out after applying all fulfillments.
*
* @param orderIndex The index of the order with the consideration
* item with a shortfall.
* @param considerationIndex The index of the consideration item on the
* order.
* @param shortfallAmount The unfulfilled consideration amount.
*/
error ConsiderationNotMet(
uint256 orderIndex,
uint256 considerationIndex,
uint256 shortfallAmount
);
/**
* @dev Revert with an error when insufficient native tokens are supplied as
* part of msg.value when fulfilling orders.
*/
error InsufficientNativeTokensSupplied();
/**
* @dev Revert with an error when a native token transfer reverts.
*/
error NativeTokenTransferGenericFailure(address account, uint256 amount);
/**
* @dev Revert with an error when a partial fill is attempted on an order
* that does not specify partial fill support in its order type.
*/
error PartialFillsNotEnabledForOrder();
/**
* @dev Revert with an error when attempting to fill an order that has been
* cancelled.
*
* @param orderHash The hash of the cancelled order.
*/
error OrderIsCancelled(bytes32 orderHash);
/**
* @dev Revert with an error when attempting to fill a basic order that has
* been partially filled.
*
* @param orderHash The hash of the partially used order.
*/
error OrderPartiallyFilled(bytes32 orderHash);
/**
* @dev Revert with an error when attempting to cancel an order as a caller
* other than the indicated offerer or zone or when attempting to
* cancel a contract order.
*/
error CannotCancelOrder();
/**
* @dev Revert with an error when supplying a fraction with a value of zero
* for the numerator or denominator, or one where the numerator exceeds
* the denominator.
*/
error BadFraction();
/**
* @dev Revert with an error when a caller attempts to supply callvalue to a
* non-payable basic order route or does not supply any callvalue to a
* payable basic order route.
*/
error InvalidMsgValue(uint256 value);
/**
* @dev Revert with an error when attempting to fill a basic order using
* calldata not produced by default ABI encoding.
*/
error InvalidBasicOrderParameterEncoding();
/**
* @dev Revert with an error when attempting to fulfill any number of
* available orders when none are fulfillable.
*/
error NoSpecifiedOrdersAvailable();
/**
* @dev Revert with an error when attempting to fulfill an order with an
* offer for a native token outside of matching orders.
*/
error InvalidNativeOfferItem();
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/**
* @title ConduitControllerInterface
* @author 0age
* @notice ConduitControllerInterface contains all external function interfaces,
* structs, events, and errors for the conduit controller.
*/
interface ConduitControllerInterface {
/**
* @dev Track the conduit key, current owner, new potential owner, and open
* channels for each deployed conduit.
*/
struct ConduitProperties {
bytes32 key;
address owner;
address potentialOwner;
address[] channels;
mapping(address => uint256) channelIndexesPlusOne;
}
/**
* @dev Emit an event whenever a new conduit is created.
*
* @param conduit The newly created conduit.
* @param conduitKey The conduit key used to create the new conduit.
*/
event NewConduit(address conduit, bytes32 conduitKey);
/**
* @dev Emit an event whenever conduit ownership is transferred.
*
* @param conduit The conduit for which ownership has been
* transferred.
* @param previousOwner The previous owner of the conduit.
* @param newOwner The new owner of the conduit.
*/
event OwnershipTransferred(
address indexed conduit,
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Emit an event whenever a conduit owner registers a new potential
* owner for that conduit.
*
* @param newPotentialOwner The new potential owner of the conduit.
*/
event PotentialOwnerUpdated(address indexed newPotentialOwner);
/**
* @dev Revert with an error when attempting to create a new conduit using a
* conduit key where the first twenty bytes of the key do not match the
* address of the caller.
*/
error InvalidCreator();
/**
* @dev Revert with an error when attempting to create a new conduit when no
* initial owner address is supplied.
*/
error InvalidInitialOwner();
/**
* @dev Revert with an error when attempting to set a new potential owner
* that is already set.
*/
error NewPotentialOwnerAlreadySet(
address conduit,
address newPotentialOwner
);
/**
* @dev Revert with an error when attempting to cancel ownership transfer
* when no new potential owner is currently set.
*/
error NoPotentialOwnerCurrentlySet(address conduit);
/**
* @dev Revert with an error when attempting to interact with a conduit that
* does not yet exist.
*/
error NoConduit();
/**
* @dev Revert with an error when attempting to create a conduit that
* already exists.
*/
error ConduitAlreadyExists(address conduit);
/**
* @dev Revert with an error when attempting to update channels or transfer
* ownership of a conduit when the caller is not the owner of the
* conduit in question.
*/
error CallerIsNotOwner(address conduit);
/**
* @dev Revert with an error when attempting to register a new potential
* owner and supplying the null address.
*/
error NewPotentialOwnerIsZeroAddress(address conduit);
/**
* @dev Revert with an error when attempting to claim ownership of a conduit
* with a caller that is not the current potential owner for the
* conduit in question.
*/
error CallerIsNotNewPotentialOwner(address conduit);
/**
* @dev Revert with an error when attempting to retrieve a channel using an
* index that is out of range.
*/
error ChannelOutOfRange(address conduit);
/**
* @notice Deploy a new conduit using a supplied conduit key and assigning
* an initial owner for the deployed conduit. Note that the first
* twenty bytes of the supplied conduit key must match the caller
* and that a new conduit cannot be created if one has already been
* deployed using the same conduit key.
*
* @param conduitKey The conduit key used to deploy the conduit. Note that
* the first twenty bytes of the conduit key must match
* the caller of this contract.
* @param initialOwner The initial owner to set for the new conduit.
*
* @return conduit The address of the newly deployed conduit.
*/
function createConduit(
bytes32 conduitKey,
address initialOwner
) external returns (address conduit);
/**
* @notice Open or close a channel on a given conduit, thereby allowing the
* specified account to execute transfers against that conduit.
* Extreme care must be taken when updating channels, as malicious
* or vulnerable channels can transfer any ERC20, ERC721 and ERC1155
* tokens where the token holder has granted the conduit approval.
* Only the owner of the conduit in question may call this function.
*
* @param conduit The conduit for which to open or close the channel.
* @param channel The channel to open or close on the conduit.
* @param isOpen A boolean indicating whether to open or close the channel.
*/
function updateChannel(
address conduit,
address channel,
bool isOpen
) external;
/**
* @notice Initiate conduit ownership transfer by assigning a new potential
* owner for the given conduit. Once set, the new potential owner
* may call `acceptOwnership` to claim ownership of the conduit.
* Only the owner of the conduit in question may call this function.
*
* @param conduit The conduit for which to initiate ownership transfer.
* @param newPotentialOwner The new potential owner of the conduit.
*/
function transferOwnership(
address conduit,
address newPotentialOwner
) external;
/**
* @notice Clear the currently set potential owner, if any, from a conduit.
* Only the owner of the conduit in question may call this function.
*
* @param conduit The conduit for which to cancel ownership transfer.
*/
function cancelOwnershipTransfer(address conduit) external;
/**
* @notice Accept ownership of a supplied conduit. Only accounts that the
* current owner has set as the new potential owner may call this
* function.
*
* @param conduit The conduit for which to accept ownership.
*/
function acceptOwnership(address conduit) external;
/**
* @notice Retrieve the current owner of a deployed conduit.
*
* @param conduit The conduit for which to retrieve the associated owner.
*
* @return owner The owner of the supplied conduit.
*/
function ownerOf(address conduit) external view returns (address owner);
/**
* @notice Retrieve the conduit key for a deployed conduit via reverse
* lookup.
*
* @param conduit The conduit for which to retrieve the associated conduit
* key.
*
* @return conduitKey The conduit key used to deploy the supplied conduit.
*/
function getKey(address conduit) external view returns (bytes32 conduitKey);
/**
* @notice Derive the conduit associated with a given conduit key and
* determine whether that conduit exists (i.e. whether it has been
* deployed).
*
* @param conduitKey The conduit key used to derive the conduit.
*
* @return conduit The derived address of the conduit.
* @return exists A boolean indicating whether the derived conduit has been
* deployed or not.
*/
function getConduit(
bytes32 conduitKey
) external view returns (address conduit, bool exists);
/**
* @notice Retrieve the potential owner, if any, for a given conduit. The
* current owner may set a new potential owner via
* `transferOwnership` and that owner may then accept ownership of
* the conduit in question via `acceptOwnership`.
*
* @param conduit The conduit for which to retrieve the potential owner.
*
* @return potentialOwner The potential owner, if any, for the conduit.
*/
function getPotentialOwner(
address conduit
) external view returns (address potentialOwner);
/**
* @notice Retrieve the status (either open or closed) of a given channel on
* a conduit.
*
* @param conduit The conduit for which to retrieve the channel status.
* @param channel The channel for which to retrieve the status.
*
* @return isOpen The status of the channel on the given conduit.
*/
function getChannelStatus(
address conduit,
address channel
) external view returns (bool isOpen);
/**
* @notice Retrieve the total number of open channels for a given conduit.
*
* @param conduit The conduit for which to retrieve the total channel count.
*
* @return totalChannels The total number of open channels for the conduit.
*/
function getTotalChannels(
address conduit
) external view returns (uint256 totalChannels);
/**
* @notice Retrieve an open channel at a specific index for a given conduit.
* Note that the index of a channel can change as a result of other
* channels being closed on the conduit.
*
* @param conduit The conduit for which to retrieve the open channel.
* @param channelIndex The index of the channel in question.
*
* @return channel The open channel, if any, at the specified channel index.
*/
function getChannel(
address conduit,
uint256 channelIndex
) external view returns (address channel);
/**
* @notice Retrieve all open channels for a given conduit. Note that calling
* this function for a conduit with many channels will revert with
* an out-of-gas error.
*
* @param conduit The conduit for which to retrieve open channels.
*
* @return channels An array of open channels on the given conduit.
*/
function getChannels(
address conduit
) external view returns (address[] memory channels);
/**
* @dev Retrieve the conduit creation code and runtime code hashes.
*/
function getConduitCodeHashes()
external
view
returns (bytes32 creationCodeHash, bytes32 runtimeCodeHash);
}