// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "./interfaces/IDSponsorMarketplace.sol";
import "./interfaces/IERC4907.sol";
import "./lib/ERC2771ContextOwnable.sol";
import "./lib/ProtocolFee.sol";
// import "hardhat/console.sol";
/**
* @title DSponsorMarketplace
* @notice This contract is a marketplace for offers, direct and auction listings of NFTs with ERC20 tokens as currency.
* Implementation from Thirdweb Markeptlace & GBM auction (% of winning bid sent to previous bidder)
*/
contract DSponsorMarketplace is
IDSponsorMarketplace,
ERC2771ContextOwnable,
ProtocolFee,
IERC721Receiver,
IERC1155Receiver
{
/*//////////////////////////////////////////////////////////////
Constants
//////////////////////////////////////////////////////////////*/
/**
* @dev The amount of time added to an auction's 'endTime', if a bid is made within `AUCTION_ENDTIME_BUFFER`
* seconds of the existing `endTime`.
*/
uint128 public constant AUCTION_ENDTIME_BUFFER = 15 minutes;
/// @dev The minimum % increase required from the previous winning bid.
uint64 public constant MIN_AUCTION_INCREASE_BPS = 1000; // 10%
/// @dev The % bonus refunded to the previous winning bidder on its bid amount.
uint64 public constant ADDITIONNAL_REFUND_PREVIOUS_BIDDER_BPS = 500; // 5%
/*///////////////////////////////////////////////////////////////
State variables
//////////////////////////////////////////////////////////////*/
/// @dev Total number of listings ever created in the marketplace.
uint256 public totalListings;
/// @dev Total number of offers ever created in the marketplace.
uint256 public totalOffers;
/// @dev Mapping from uid of listing => listing info.
mapping(uint256 => Listing) public listings;
/// @dev Mapping from uid of an auction listing => current winning bid in an auction.
mapping(uint256 => Bid) public winningBid;
mapping(uint256 => Offer) public offers;
/*///////////////////////////////////////////////////////////////
Modifiers
//////////////////////////////////////////////////////////////*/
/// @dev Checks whether caller is a listing creator.
modifier onlyListingCreator(uint256 _listingId) {
if (listings[_listingId].tokenOwner != _msgSender()) {
revert SenderIsNotTokenOwner();
}
_;
}
/// @dev Checks whether a listing exists.
modifier onlyExistingListing(uint256 _listingId) {
if (listings[_listingId].assetContract == address(0)) {
revert ListingDoesNotExist(uint256(_listingId));
}
_;
}
/// @dev Checks whether caller is a offer creator.
modifier onlyOfferor(uint256 _offerId) {
if (offers[_offerId].offeror != _msgSender()) {
revert SenderIsNotOfferor();
}
_;
}
/// @dev Checks whether an auction exists.
modifier onlyExistingOffer(uint256 _offerId) {
if (offers[_offerId].status != Status.CREATED) {
revert OfferIsNotActive(uint256(_offerId));
}
_;
}
/*///////////////////////////////////////////////////////////////
Constructor
//////////////////////////////////////////////////////////////*/
constructor(
address forwarder,
address initialOwner,
UniV3SwapRouter _swapRouter,
address payable _recipient,
uint96 _bps
)
ERC2771ContextOwnable(forwarder, initialOwner)
ProtocolFee(_swapRouter, _recipient, _bps)
{
assert(
MIN_AUCTION_INCREASE_BPS > ADDITIONNAL_REFUND_PREVIOUS_BIDDER_BPS
);
assert(MIN_AUCTION_INCREASE_BPS < 10000);
}
/*///////////////////////////////////////////////////////////////
ERC 165 / 721 / 1155 logic
//////////////////////////////////////////////////////////////*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return this.onERC721Received.selector;
}
function supportsInterface(
bytes4 interfaceId
) public view virtual override(IERC165) returns (bool) {
return
interfaceId == type(IERC1155Receiver).interfaceId ||
interfaceId == type(IERC721Receiver).interfaceId;
}
/*///////////////////////////////////////////////////////////////
Listing (create-update-delete) logic
//////////////////////////////////////////////////////////////*/
/// @dev Lets a token owner list tokens for sale: Direct Listing or Auction.
function createListing(ListingParameters memory _params) external {
_validateTransferType(_params.assetContract, _params.transferType);
if (
_params.transferType == TransferType.Rent &&
_params.rentalExpirationTimestamp <
(_params.startTime + _params.secondsUntilEndTime)
) {
revert InvalidRentalExpiration();
}
// Get values to populate `Listing`.
uint256 listingId = totalListings;
totalListings += 1;
address tokenOwner = _msgSender();
TokenType tokenTypeOfListing = _getTokenType(_params.assetContract);
uint256 tokenAmountToList = _getSafeQuantity(
tokenTypeOfListing,
_params.quantityToList
);
if (tokenAmountToList == 0) {
revert ZeroQuantity();
}
uint256 startTime = _params.startTime;
if (startTime < block.timestamp) {
// do not allow listing to start in the past
startTime = block.timestamp;
}
_validateOwnershipAndApproval(
tokenOwner,
_params.assetContract,
_params.tokenId,
tokenAmountToList,
tokenTypeOfListing,
_params.transferType,
_params.rentalExpirationTimestamp
);
Listing memory newListing = Listing({
listingId: listingId,
tokenOwner: tokenOwner,
assetContract: _params.assetContract,
tokenId: _params.tokenId,
startTime: startTime,
endTime: startTime + _params.secondsUntilEndTime,
quantity: tokenAmountToList,
currency: _params.currencyToAccept,
reservePricePerToken: _params.reservePricePerToken,
buyoutPricePerToken: _params.buyoutPricePerToken,
tokenType: tokenTypeOfListing,
transferType: _params.transferType,
rentalExpirationTimestamp: _params.rentalExpirationTimestamp,
listingType: _params.listingType
});
listings[listingId] = newListing;
// Tokens listed for sale in an auction are escrowed in Marketplace.
if (newListing.listingType == ListingType.Auction) {
if (
newListing.buyoutPricePerToken > 0 &&
newListing.buyoutPricePerToken < newListing.reservePricePerToken
) {
revert InvalidPricingParameters();
}
_transferListingTokens(
tokenOwner,
address(this),
tokenAmountToList,
newListing
);
}
emit ListingAdded(
listingId,
_params.assetContract,
tokenOwner,
newListing
);
}
/// @dev Lets a listing's creator edit the listing's parameters.
function updateListing(
uint256 _listingId,
ListingUpdateParameters memory _params
) external onlyListingCreator(_listingId) {
Listing memory targetListing = listings[_listingId];
uint256 safeNewQuantity = _getSafeQuantity(
targetListing.tokenType,
_params.quantityToList
);
bool isAuction = targetListing.listingType == ListingType.Auction;
if (safeNewQuantity == 0) {
revert ZeroQuantity();
}
// Can only edit auction listing before it starts.
if (isAuction) {
if (block.timestamp > targetListing.startTime) {
revert AuctionAlreadyStarted();
}
if (
_params.buyoutPricePerToken > 0 &&
_params.buyoutPricePerToken < _params.reservePricePerToken
) {
revert InvalidPricingParameters();
}
}
if (_params.startTime > 0 && _params.startTime < block.timestamp) {
// do not allow listing to start in the past
_params.startTime = block.timestamp;
}
uint256 newStartTime = _params.startTime == 0
? targetListing.startTime
: _params.startTime;
uint256 endTime = _params.secondsUntilEndTime == 0
? targetListing.endTime
: newStartTime + _params.secondsUntilEndTime;
if (
targetListing.transferType == TransferType.Rent &&
_params.rentalExpirationTimestamp < endTime
) {
revert InvalidRentalExpiration();
}
listings[_listingId] = Listing({
listingId: _listingId,
tokenOwner: _msgSender(),
assetContract: targetListing.assetContract,
tokenId: targetListing.tokenId,
startTime: newStartTime,
endTime: endTime,
quantity: safeNewQuantity,
currency: _params.currencyToAccept,
reservePricePerToken: _params.reservePricePerToken,
buyoutPricePerToken: _params.buyoutPricePerToken,
tokenType: targetListing.tokenType,
transferType: targetListing.transferType,
rentalExpirationTimestamp: targetListing.rentalExpirationTimestamp,
listingType: targetListing.listingType
});
// Must validate ownership and approval of the new quantity of tokens for direct listing.
if (targetListing.quantity != safeNewQuantity) {
// Transfer all escrowed tokens back to the lister, to be reflected in the lister's
// balance for the upcoming ownership and approval check.
if (isAuction) {
_transferListingTokens(
address(this),
targetListing.tokenOwner,
targetListing.quantity,
targetListing
);
}
_validateOwnershipAndApproval(
targetListing.tokenOwner,
targetListing.assetContract,
targetListing.tokenId,
safeNewQuantity,
targetListing.tokenType,
targetListing.transferType,
targetListing.rentalExpirationTimestamp
);
// Escrow the new quantity of tokens to list in the auction.
if (isAuction) {
_transferListingTokens(
targetListing.tokenOwner,
address(this),
safeNewQuantity,
targetListing
);
}
}
emit ListingUpdated(_listingId, targetListing.tokenOwner, _params);
}
/// @dev Lets a direct listing creator cancel their listing.
function cancelDirectListing(
uint256 _listingId
) external onlyListingCreator(_listingId) {
Listing memory targetListing = listings[_listingId];
if (targetListing.listingType != ListingType.Direct) {
revert IsNotDirectListing();
}
delete listings[_listingId];
emit ListingRemoved(_listingId, targetListing.tokenOwner);
}
/*///////////////////////////////////////////////////////////////
Direct listings sales logic
//////////////////////////////////////////////////////////////*/
/**
* @dev Buy from a direct listing with the option to pay with native currency
* (to allow payment with delegated payment systems, payment by credit card)
*/
function buy(BuyParams calldata buyParams) external payable nonReentrant {
uint256 sentValue = msg.value;
address payer = _msgSender();
if (buyParams.buyFor == address(0)) {
revert CannotBeZeroAddress();
}
uint256 totalPrice = listings[buyParams.listingId].buyoutPricePerToken *
buyParams.quantity;
// Swap native currency to ERC20 if value is sent
if (sentValue > 0) {
// refund to "spender" once swap done,
// and not _msgSender() as it can be the address of a delegating payment system
address recipientRefund = buyParams.buyFor;
_swapNativeToERC20(
buyParams.currency,
totalPrice,
sentValue,
recipientRefund
);
payer = address(this);
}
_buy(
buyParams.listingId,
payer,
buyParams.buyFor,
buyParams.quantity,
buyParams.currency,
totalPrice,
buyParams.referralAdditionalInformation
);
}
/// @dev Lets an account buy a given quantity of tokens from a listing.
function _buy(
uint256 _listingId,
address _payer,
address _buyFor,
uint256 _quantityToBuy,
address _currency,
uint256 _totalPrice,
string memory referralAdditionalInformation
) internal onlyExistingListing(_listingId) {
Listing memory targetListing = listings[_listingId];
if (targetListing.listingType != ListingType.Direct) {
revert IsNotDirectListing();
}
// Check whether the settled total price and currency to use are correct.
if (_currency != targetListing.currency) {
revert InvalidCurrency();
}
if (_totalPrice != targetListing.buyoutPricePerToken * _quantityToBuy) {
revert InvalidTotalPrice();
}
// Check whether a valid quantity of listed tokens is being bought.
if (_quantityToBuy == 0) {
revert ZeroQuantity();
}
if (_quantityToBuy > targetListing.quantity) {
revert OutOfStock();
}
// Check if sale is made within the listing window.
if (
block.timestamp > targetListing.endTime ||
block.timestamp < targetListing.startTime
) {
revert OutOfValidityPeriod();
}
// Check whether token owner owns and has approved `quantityToBuy` amount of listing tokens from the listing.
_validateOwnershipAndApproval(
targetListing.tokenOwner,
targetListing.assetContract,
targetListing.tokenId,
_quantityToBuy,
targetListing.tokenType,
targetListing.transferType,
targetListing.rentalExpirationTimestamp
);
ReferralRevenue memory referral = ReferralRevenue({
enabler: targetListing.tokenOwner,
spender: _buyFor,
additionalInformation: referralAdditionalInformation
});
targetListing.quantity -= _quantityToBuy;
listings[_listingId] = targetListing;
_payout(
_payer,
targetListing.tokenOwner,
_currency,
_totalPrice,
targetListing.assetContract,
targetListing.tokenId,
referral
);
_transferListingTokens(
targetListing.tokenOwner,
_buyFor,
_quantityToBuy,
targetListing
);
emit NewSale(
_listingId,
targetListing.assetContract,
targetListing.tokenOwner,
_buyFor,
_quantityToBuy,
_totalPrice
);
}
/*///////////////////////////////////////////////////////////////
Auction listings sales logic
//////////////////////////////////////////////////////////////*/
/// @dev Bid in an auction. Previous bidder is reimbursed with a % bonus.
function bid(
uint256 _listingId,
uint256 _pricePerToken,
address _bidder,
string memory _referralAdditionalInformation
) external payable nonReentrant onlyExistingListing(_listingId) {
Listing memory targetListing = listings[_listingId];
Bid memory currentWinningBid = winningBid[_listingId];
// bidder cannot be 0 address
if (_bidder == address(0)) {
revert CannotBeZeroAddress();
}
// cannot bid if the listing is not an auction
if (targetListing.listingType != ListingType.Auction) {
revert IsNotAuctionListing();
}
// Check if sale is made within the listing window.
if (
block.timestamp > targetListing.endTime ||
block.timestamp < targetListing.startTime
) {
revert OutOfValidityPeriod();
}
// checks on quantity
uint256 quantity = _getSafeQuantity(
targetListing.tokenType,
targetListing.quantity
);
if (quantity == 0) {
revert ZeroQuantity();
}
// check if incoming bid is higher than the current winning bid or reserve price
uint256 requiredMinimalPricePerToken = currentWinningBid
.pricePerToken == 0
? targetListing.reservePricePerToken
: currentWinningBid.pricePerToken +
((MIN_AUCTION_INCREASE_BPS * currentWinningBid.pricePerToken) /
10000);
if (requiredMinimalPricePerToken > _pricePerToken) {
revert isNotWinningBid();
}
// Calculate refund amount to previous bidder
uint256 refundBonusPerToken = (ADDITIONNAL_REFUND_PREVIOUS_BIDDER_BPS *
currentWinningBid.pricePerToken) / 10000;
uint256 refundAmountToPreviousBidder = quantity *
(currentWinningBid.pricePerToken + refundBonusPerToken);
if (refundAmountToPreviousBidder >= (_pricePerToken * quantity)) {
revert RefundExceedsBid();
}
// Collect incoming bid
if (msg.value > 0) {
// Swap native currency to ERC20 if value is sent
_swapNativeToERC20(
targetListing.currency,
_pricePerToken * quantity,
msg.value,
_bidder // refund to "spender" once swap done, and not _msgSender() as it can be the address of a delegating payment system
);
} else {
_pay(
_msgSender(),
address(this),
targetListing.currency,
_pricePerToken * quantity
);
}
_bid(
_listingId,
quantity,
_bidder,
_pricePerToken - refundBonusPerToken,
refundBonusPerToken,
refundAmountToPreviousBidder,
_referralAdditionalInformation
);
}
function _bid(
uint256 _listingId,
uint256 quantity,
address newBidder,
uint256 newPricePerToken,
uint256 refundBonusPerToken,
uint256 refundAmountToPreviousBidder,
string memory _referralAdditionalInformation
) internal {
Listing memory targetListing = listings[_listingId];
address previousBidder = winningBid[_listingId].bidder;
Bid memory newBid = Bid({
listingId: _listingId,
bidder: newBidder,
pricePerToken: newPricePerToken,
referralAdditionalInformation: _referralAdditionalInformation
});
if (targetListing.endTime - block.timestamp <= AUCTION_ENDTIME_BUFFER) {
targetListing.endTime += AUCTION_ENDTIME_BUFFER;
listings[targetListing.listingId] = targetListing;
}
// @dev Emit NewBid event before close auction to be able to construct the subgraph correctly
emit NewBid(
targetListing.listingId,
quantity,
newBidder,
newPricePerToken,
previousBidder,
refundBonusPerToken * quantity,
targetListing.currency,
targetListing.endTime
);
// Close auction and execute sale if there's a buyout price and incoming bid amount is buyout price.
if (
targetListing.buyoutPricePerToken > 0 &&
newPricePerToken >= targetListing.buyoutPricePerToken
) {
_closeAuction(targetListing, newBid);
} else {
winningBid[targetListing.listingId] = newBid;
}
// Payout previous highest bid.
if (refundAmountToPreviousBidder > 0) {
_pay(
address(this),
previousBidder,
targetListing.currency,
refundAmountToPreviousBidder
);
}
}
/**
* @dev Lets an account close an auction
* (distribute winning bid amount to auction creator and distribute auction items to the winning bidder)
*/
function closeAuction(
uint256 _listingId
) external nonReentrant onlyExistingListing(_listingId) {
Listing memory targetListing = listings[_listingId];
if (targetListing.listingType != ListingType.Auction) {
revert IsNotAuctionListing();
}
Bid memory targetBid = winningBid[_listingId];
// Cancel auction if (1) auction hasn't started, or (2) auction doesn't have any bids.
bool toCancel = targetListing.startTime > block.timestamp ||
targetBid.bidder == address(0);
if (toCancel) {
// cancel auction listing owner check
_cancelAuction(targetListing);
} else {
if (targetListing.endTime > block.timestamp) {
revert AuctionStillActive();
}
_closeAuction(targetListing, targetBid);
}
}
/// @dev Cancels an auction.
function _cancelAuction(Listing memory _targetListing) internal {
if (listings[_targetListing.listingId].tokenOwner != _msgSender()) {
revert SenderIsNotTokenOwner();
}
delete listings[_targetListing.listingId];
_transferListingTokens(
address(this),
_targetListing.tokenOwner,
_targetListing.quantity,
_targetListing
);
emit AuctionClosed(
_targetListing.listingId,
_msgSender(),
true,
_targetListing.tokenOwner,
address(0)
);
}
function _closeAuction(
Listing memory _targetListing,
Bid memory _winningBid
) internal {
uint256 payoutAmount = _winningBid.pricePerToken *
_targetListing.quantity;
_targetListing.quantity = 0;
_targetListing.endTime = block.timestamp;
listings[_targetListing.listingId] = _targetListing;
winningBid[_targetListing.listingId] = _winningBid;
ReferralRevenue memory referral = ReferralRevenue({
enabler: _targetListing.tokenOwner,
spender: _winningBid.bidder,
additionalInformation: _winningBid.referralAdditionalInformation
});
_payout(
address(this),
_targetListing.tokenOwner,
_targetListing.currency,
payoutAmount,
_targetListing.assetContract,
_targetListing.tokenId,
referral
);
_transferListingTokens(
address(this),
_winningBid.bidder,
_targetListing.quantity,
_targetListing
);
emit AuctionClosed(
_targetListing.listingId,
_msgSender(),
false,
_targetListing.tokenOwner,
_winningBid.bidder
);
}
/*///////////////////////////////////////////////////////////////
Offers logic
//////////////////////////////////////////////////////////////*/
function makeOffer(
OfferParams memory _params
) external returns (uint256 _offerId) {
_offerId = totalOffers;
totalOffers += 1;
address _offeror = _msgSender();
TokenType _tokenType = _getTokenType(_params.assetContract);
_validateTransferType(_params.assetContract, _params.transferType);
_validateNewOffer(_params, _tokenType);
Offer memory _offer = Offer({
offerId: _offerId,
offeror: _offeror,
assetContract: _params.assetContract,
tokenId: _params.tokenId,
tokenType: _tokenType,
quantity: _params.quantity,
currency: _params.currency,
totalPrice: _params.totalPrice,
expirationTimestamp: _params.expirationTimestamp,
transferType: _params.transferType,
rentalExpirationTimestamp: _params.rentalExpirationTimestamp,
status: Status.CREATED,
referralAdditionalInformation: _params.referralAdditionalInformation
});
offers[_offerId] = _offer;
emit NewOffer(_offeror, _offerId, _params.assetContract, _offer);
}
function cancelOffer(
uint256 _offerId
) external onlyExistingOffer(_offerId) onlyOfferor(_offerId) {
offers[_offerId].status = Status.CANCELLED;
emit CancelledOffer(_msgSender(), _offerId);
}
function acceptOffer(
uint256 _offerId
) external nonReentrant onlyExistingOffer(_offerId) {
Offer memory _targetOffer = offers[_offerId];
if (_targetOffer.expirationTimestamp < block.timestamp) {
revert OutOfValidityPeriod();
}
if (
!_validateERC20BalAndAllowance(
_targetOffer.offeror,
_targetOffer.currency,
_targetOffer.totalPrice
)
) {
revert InsufficientAllowanceOrBalance(_targetOffer.currency);
}
_validateOwnershipAndApproval(
_msgSender(),
_targetOffer.assetContract,
_targetOffer.tokenId,
_targetOffer.quantity,
_targetOffer.tokenType,
_targetOffer.transferType,
_targetOffer.rentalExpirationTimestamp
);
offers[_offerId].status = Status.COMPLETED;
ReferralRevenue memory referral = ReferralRevenue({
enabler: _msgSender(),
spender: _targetOffer.offeror,
additionalInformation: _targetOffer.referralAdditionalInformation
});
_payout(
_targetOffer.offeror,
_msgSender(),
_targetOffer.currency,
_targetOffer.totalPrice,
_targetOffer.assetContract,
_targetOffer.tokenId,
referral
);
_transferOfferTokens(
_msgSender(),
_targetOffer.offeror,
_targetOffer.quantity,
_targetOffer
);
emit AcceptedOffer(
_targetOffer.offeror,
_targetOffer.offerId,
_targetOffer.assetContract,
_targetOffer.tokenId,
_msgSender(),
_targetOffer.quantity,
_targetOffer.totalPrice
);
}
/// @dev Checks whether the auction creator owns and has approved marketplace to transfer auctioned tokens.
function _validateNewOffer(
OfferParams memory _params,
TokenType _tokenType
) internal view {
if (_params.totalPrice == 0) {
revert InvalidTotalPrice();
}
if (_params.quantity == 0) {
revert ZeroQuantity();
}
if (_params.quantity > 1 && _tokenType != TokenType.ERC1155) {
revert InvalidQuantity();
}
if (_params.expirationTimestamp < block.timestamp) {
revert OutOfValidityPeriod();
}
if (
_params.transferType == TransferType.Rent &&
_params.rentalExpirationTimestamp < _params.expirationTimestamp
) {
revert InvalidRentalExpiration();
}
if (
!_validateERC20BalAndAllowance(
_msgSender(),
_params.currency,
_params.totalPrice
)
) {
revert InsufficientAllowanceOrBalance(_params.currency);
}
}
/*//////////////////////////////////////////////////////////////
Shared internal functions
//////////////////////////////////////////////////////////////*/
function _transferListingTokens(
address _from,
address _to,
uint256 _quantity,
Listing memory _listing
) internal {
_transferTokens(
_listing.transferType,
_listing.assetContract,
_from,
_to,
_quantity,
_listing.rentalExpirationTimestamp,
_listing.tokenId,
_listing.tokenType
);
}
function _transferOfferTokens(
address _from,
address _to,
uint256 _quantity,
Offer memory _offer
) internal {
_transferTokens(
_offer.transferType,
_offer.assetContract,
_from,
_to,
_quantity,
_offer.rentalExpirationTimestamp,
_offer.tokenId,
_offer.tokenType
);
}
function _transferTokens(
TransferType _transferType,
address _assetContract,
address _from,
address _to,
uint256 _quantity,
uint64 _rentalExpirationTimestamp,
uint256 _tokenId,
TokenType _tokenType
) internal {
if (_tokenType == TokenType.ERC1155) {
IERC1155(_assetContract).safeTransferFrom(
_from,
_to,
_tokenId,
_quantity,
""
);
} else if (_tokenType == TokenType.ERC721) {
if (_transferType == TransferType.Rent) {
IERC4907(_assetContract).setUser(
_tokenId,
_to,
_rentalExpirationTimestamp
);
} else {
IERC721(_assetContract).safeTransferFrom(
_from,
_to,
_tokenId,
""
);
}
}
}
/// @dev Pays out stakeholders in a sale.
function _payout(
address _payer,
address _payee,
address _currencyToUse,
uint256 _totalPayoutAmount,
address _assetContract,
uint256 _tokenId,
ReferralRevenue memory referral
) internal {
// Pay protocol fee
uint256 protocolCut = getFeeAmount(_totalPayoutAmount);
_payFee(_payer, _currencyToUse, protocolCut, address(this), referral);
// Distribute royalties
uint256 royaltyCut;
address royaltyRecipient;
try
IERC2981(_assetContract).royaltyInfo(_tokenId, _totalPayoutAmount)
returns (address royaltyFeeRecipient, uint256 royaltyFeeAmount) {
if (royaltyFeeRecipient != address(0) && royaltyFeeAmount > 0) {
royaltyRecipient = royaltyFeeRecipient;
royaltyCut = royaltyFeeAmount;
}
} catch {}
_pay(_payer, royaltyRecipient, _currencyToUse, royaltyCut);
// Pay to the payee
_pay(
_payer,
_payee,
_currencyToUse,
_totalPayoutAmount - protocolCut - royaltyCut
);
}
/// @dev Validates that `_tokenOwner` owns and has approved Markeplace to transfer the appropriate amount of currency
function _validateERC20BalAndAllowance(
address _tokenOwner,
address _currency,
uint256 _amount
) internal view returns (bool isValid) {
isValid =
IERC20(_currency).balanceOf(_tokenOwner) >= _amount &&
IERC20(_currency).allowance(_tokenOwner, address(this)) >= _amount;
}
/// @dev Validates that `_tokenOwner` owns and has approved Market to transfer/rent NFTs
function _validateOwnershipAndApproval(
address _tokenOwner,
address _assetContract,
uint256 _tokenId,
uint256 _quantity,
TokenType _tokenType,
TransferType _transferType,
uint64 _rentalExpirationTimestamp
) internal view {
address market = address(this);
bool isValid = false;
if (
_tokenType == TokenType.ERC1155 &&
_transferType != TransferType.Rent
) {
isValid =
IERC1155(_assetContract).balanceOf(_tokenOwner, _tokenId) >=
_quantity &&
IERC1155(_assetContract).isApprovedForAll(_tokenOwner, market);
} else if (_tokenType == TokenType.ERC721) {
isValid =
IERC721(_assetContract).ownerOf(_tokenId) == _tokenOwner &&
(IERC721(_assetContract).getApproved(_tokenId) == market ||
IERC721(_assetContract).isApprovedForAll(
_tokenOwner,
market
));
if (
_transferType == TransferType.Rent &&
IERC4907(_assetContract).userOf(_tokenId) != address(0) &&
IERC4907(_assetContract).userOf(_tokenId) !=
IERC721(_assetContract).ownerOf(_tokenId)
) {
isValid =
IERC4907(_assetContract).userOf(_tokenId) == _tokenOwner &&
IERC721(_assetContract).isApprovedForAll(
_tokenOwner,
market
) &&
IERC4907(_assetContract).userExpires(_tokenId) >=
_rentalExpirationTimestamp;
}
}
if (!isValid) {
revert InsufficientAllowanceOrBalance(_assetContract);
}
}
/// @dev Check if is valid transfer type
function _validateTransferType(
address assetContract,
TransferType _transferType
) internal view {
bool isValid = _transferType == TransferType.Sale ||
IERC165(assetContract).supportsInterface(
type(IERC4907).interfaceId
);
if (!isValid) {
revert NotERC4907Compliant();
}
}
/*//////////////////////////////////////////////////////////////
Getter functions
//////////////////////////////////////////////////////////////*/
/// @dev Enforces quantity == 1 if tokenType is TokenType.ERC721.
function _getSafeQuantity(
TokenType _tokenType,
uint256 _quantityToCheck
) internal pure returns (uint256 safeQuantity) {
if (_quantityToCheck == 0) {
safeQuantity = 0;
} else {
safeQuantity = _tokenType == TokenType.ERC721
? 1
: _quantityToCheck;
}
}
/// @dev Returns the interface supported by a contract.
function _getTokenType(
address _assetContract
) internal view returns (TokenType tokenType) {
if (
IERC165(_assetContract).supportsInterface(
type(IERC1155).interfaceId
)
) {
tokenType = TokenType.ERC1155;
} else if (
IERC165(_assetContract).supportsInterface(type(IERC721).interfaceId)
) {
tokenType = TokenType.ERC721;
} else {
revert NotERC721OrERC1155();
}
}
/*//////////////////////////////////////////////////////////////
Miscellaneous
//////////////////////////////////////////////////////////////*/
function _msgSender()
internal
view
virtual
override(Context, ERC2771ContextOwnable)
returns (address sender)
{
return ERC2771ContextOwnable._msgSender();
}
function _msgData()
internal
view
virtual
override(Context, ERC2771ContextOwnable)
returns (bytes calldata)
{
return ERC2771ContextOwnable._msgData();
}
function _contextSuffixLength()
internal
view
virtual
override(Context, ERC2771ContextOwnable)
returns (uint256)
{
return ERC2771ContextOwnable._contextSuffixLength();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @title ERC2771ContextOwnable
* @author Anthony Gourraud
* @notice Enable gasless transactions using EIP2771 Approach, forwarder can be updated by owner
* @dev Code from OZ's ERC2771Context smart contract
*/
abstract contract ERC2771ContextOwnable is Ownable {
address private _trustedForwarder;
constructor(address forwarder, address initialOwner) Ownable(initialOwner) {
_trustedForwarder = forwarder;
}
/**
* @dev Update the address of the trusted forwarder.
*/
function setTrustedForwarder(address forwarder) external onlyOwner {
// slither-disable-next-line missing-zero-check
_trustedForwarder = forwarder;
}
/**
* @dev Returns the address of the trusted forwarder.
*/
function trustedForwarder() public view returns (address) {
return _trustedForwarder;
}
/**
* @dev Indicates whether any particular address is the trusted forwarder.
*/
function isTrustedForwarder(
address forwarder
) public view virtual returns (bool) {
return forwarder == trustedForwarder();
}
/**
* @dev Override for `msg.sender`. Defaults to the original `msg.sender` whenever
* a call is not performed by the trusted forwarder or the calldata length is less than
* 20 bytes (an address length).
*/
function _msgSender() internal view virtual override returns (address) {
uint256 calldataLength = msg.data.length;
uint256 contextSuffixLength = _contextSuffixLength();
if (
isTrustedForwarder(msg.sender) &&
calldataLength >= contextSuffixLength
) {
return
address(
bytes20(msg.data[calldataLength - contextSuffixLength:])
);
} else {
return super._msgSender();
}
}
/**
* @dev Override for `msg.data`. Defaults to the original `msg.data` whenever
* a call is not performed by the trusted forwarder or the calldata length is less than
* 20 bytes (an address length).
*/
function _msgData()
internal
view
virtual
override
returns (bytes calldata)
{
uint256 calldataLength = msg.data.length;
uint256 contextSuffixLength = _contextSuffixLength();
if (
isTrustedForwarder(msg.sender) &&
calldataLength >= contextSuffixLength
) {
return msg.data[:calldataLength - contextSuffixLength];
} else {
return super._msgData();
}
}
/**
* @dev ERC-2771 specifies the context as being a single address (20 bytes).
*/
function _contextSuffixLength()
internal
view
virtual
override
returns (uint256)
{
return 20;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
interface IDSponsorMarketplace {
enum TokenType {
ERC1155,
ERC721,
ERC20
}
enum TransferType {
Rent,
Sale
}
enum Status {
UNSET,
CREATED,
COMPLETED,
CANCELLED
}
/**
* @notice The two types of listings.
* `Direct`: NFTs listed for sale at a fixed price.
* `Auction`: NFTs listed for sale in an auction.
*/
enum ListingType {
Direct,
Auction
}
error AuctionAlreadyStarted();
error AuctionStillActive();
error CannotBeZeroAddress();
error InsufficientAllowanceOrBalance(address assetContract);
error InvalidCurrency();
error InvalidPricingParameters();
error InvalidRentalExpiration();
error InvalidTotalPrice();
error InvalidQuantity();
error IsNotAuctionListing();
error IsNotDirectListing();
error isNotWinningBid();
error ListingDoesNotExist(uint256 listingId);
error NotERC4907Compliant();
error NotERC721OrERC1155();
error OfferIsNotActive(uint256 offerId);
error OutOfStock();
error OutOfValidityPeriod();
error RefundExceedsBid();
error SenderIsNotOfferor();
error SenderIsNotTokenOwner();
error ZeroQuantity();
/**
* @notice The information related to a direct listing buy.
*
* @param listingId The uid of the direct listing to buy from.
* @param buyFor The receiver of the NFT being bought.
* @param quantity The amount of NFTs to buy from the direct listing.
* @param currency The currency to pay the price in.
* @param referralAdditionalInformation Additional information for facilitating transactions, such as business referrer IDs or tracking codes.
*
* @dev A sale will fail to execute if either:
* (1) buyer does not own or has not approved Marketplace to transfer the appropriate
* amount of currency (or hasn't sent the appropriate amount of native tokens)
*
* (2) the lister does not own or has removed Marketplace's
* approval to transfer the tokens listed for sale.
*/
struct BuyParams {
uint256 listingId;
address buyFor;
uint256 quantity;
address currency;
string referralAdditionalInformation;
}
/**
* @notice The information related to a bid in an auction.
*
* @param listingId The uid of the listing the bid is made to.
* @param bidder The account making the bid.
* @param quantityWanted The entire listing quantity
* @param currency The currency in which the bid is made.
* @param pricePerToken The price per token bidded to the lister.
* @param referralAdditionalInformation Additional information for facilitating transactions, such as business referrer IDs or tracking codes.
*/
struct Bid {
uint256 listingId;
address bidder;
uint256 pricePerToken;
string referralAdditionalInformation;
}
/**
* @dev For use in `createListing` as a parameter type.
*
* @param assetContract The contract address of the NFT to list for sale.
*
* @param tokenId The tokenId on `assetContract` of the NFT to list for sale.
*
* @param startTime The unix timestamp after which the listing is active. For direct listings:
* 'active' means NFTs can be bought from the listing. For auctions,
* 'active' means bids can be made in the auction.
*
* @param secondsUntilEndTime No. of seconds after `startTime`, after which the listing is inactive.
* For direct listings: 'inactive' means NFTs cannot be bought from the listing.
* For auctions: 'inactive' means bids can no longer be made in the auction.
*
* @param quantityToList The quantity of NFT of ID `tokenId` on the given `assetContract` to list. For
* ERC 721 tokens to list for sale, the contract strictly defaults this to `1`,
* Regardless of the value of `quantityToList` passed.
*
* @param currencyToAccept For direct listings: the currency in which a buyer must pay the listing's fixed price
* to buy the NFT(s). For auctions: the currency in which the bidders must make bids.
*
* @param reservePricePerToken For direct listings: this value is ignored. For auctions: the minimum bid amount of
* the auction is `reservePricePerToken * quantityToList`
*
* @param buyoutPricePerToken For direct listings: interpreted as 'price per token' listed. For auctions: if
* `buyoutPricePerToken` is greater than 0, and a bidder's bid is at least as great as
* `buyoutPricePerToken * quantityToList`, the bidder wins the auction, and the auction
* is closed.
*
* @param transferType The type of transfer to be made : rent or sale. Rent is only possible if `assetContract` is ERC4907.
*
* @param rentalExpirationTimestamp The date after which the rental is expired. This is only applicable if `transferType` is `Rent`.
*
* @param listingType The type of listing to create - a direct listing or an auction.
*/
struct ListingParameters {
address assetContract;
uint256 tokenId;
uint256 startTime;
uint256 secondsUntilEndTime;
uint256 quantityToList;
address currencyToAccept;
uint256 reservePricePerToken;
uint256 buyoutPricePerToken;
TransferType transferType;
uint64 rentalExpirationTimestamp;
ListingType listingType;
}
/**
* @dev For use in `updateListing` as a parameter type.
* @param quantityToList The amount of NFTs to list for sale in the listing. For direct listings, the contract
* only checks whether the listing creator owns and has approved Marketplace to transfer
* `quantityToList` amount of NFTs to list for sale. For auction listings, the contract
* ensures that exactly `quantityToList` amount of NFTs to list are escrowed.
*
* @param reservePricePerToken For direct listings: this value is ignored. For auctions: the minimum bid amount of
* the auction is `reservePricePerToken * quantityToList`
*
* @param buyoutPricePerToken For direct listings: interpreted as 'price per token' listed. For auctions: if
* `buyoutPricePerToken` is greater than 0, and a bidder's bid is at least as great as
* `buyoutPricePerToken * quantityToList`, the bidder wins the auction, and the auction
* is closed.
*
* @param currencyToAccept For direct listings: the currency in which a buyer must pay the listing's fixed price
* to buy the NFT(s). For auctions: the currency in which the bidders must make bids.
*
* @param startTime The unix timestamp after which listing is active. For direct listings:
* 'active' means NFTs can be bought from the listing. For auctions,
* 'active' means bids can be made in the auction.
*
* @param secondsUntilEndTime No. of seconds after the provided `startTime`, after which the listing is inactive.
* For direct listings: 'inactive' means NFTs cannot be bought from the listing.
* For auctions: 'inactive' means bids can no longer be made in the auction.
*
* @param rentalExpirationTimestamp The date after which the rental is expired. This is only applicable if `transferType` is `Rent`.
*/
struct ListingUpdateParameters {
uint256 quantityToList;
uint256 reservePricePerToken;
uint256 buyoutPricePerToken;
address currencyToAccept;
uint256 startTime;
uint256 secondsUntilEndTime;
uint64 rentalExpirationTimestamp;
}
/**
* @notice The information related to a listing; either (1) a direct listing, or (2) an auction listing.
*
* @dev For direct listings:
* (1) `reservePricePerToken` is ignored.
* (2) `buyoutPricePerToken` is simply interpreted as 'price per token'.
*
* @param listingId The uid for the listing.
*
* @param tokenOwner The owner of the tokens listed for sale.
*
* @param assetContract The contract address of the NFT to list for sale.
* @param tokenId The tokenId on `assetContract` of the NFT to list for sale.
* @param startTime The unix timestamp after which the listing is active. For direct listings:
* 'active' means NFTs can be bought from the listing. For auctions,
* 'active' means bids can be made in the auction.
*
* @param endTime The timestamp after which the listing is inactive.
* For direct listings: 'inactive' means NFTs cannot be bought from the listing.
* For auctions: 'inactive' means bids can no longer be made in the auction.
*
* @param quantity The quantity of NFT of ID `tokenId` on the given `assetContract` listed. For
* ERC 721 tokens to list for sale, the contract strictly defaults this to `1`,
* Regardless of the value of `quantityToList` passed.
*
* @param currency For direct listings: the currency in which a buyer must pay the listing's fixed price
* to buy the NFT(s). For auctions: the currency in which the bidders must make bids.
*
* @param reservePricePerToken For direct listings: this value is ignored. For auctions: the minimum bid amount of
* the auction is `reservePricePerToken * quantityToList`
*
* @param buyoutPricePerToken For direct listings: interpreted as 'price per token' listed. For auctions: if
* `buyoutPricePerToken` is greater than 0, and a bidder's bid is at least as great as
* `buyoutPricePerToken * quantityToList`, the bidder wins the auction, and the auction
* is closed.
*
* @param tokenType The type of the token(s) listed for for sale -- ERC721 or ERC1155
*
* @param transferType The type of transfer to be made : rent or sale. Rent is only possible if `assetContract` is ERC4907.
*
* @param rentalExpirationTimestamp The date after which the rental is expired. This is only applicable if `transferType` is `Rent`.
*
* @param listingType The type of listing to create - a direct listing or an auction.
**/
struct Listing {
uint256 listingId;
address tokenOwner;
address assetContract;
uint256 tokenId;
uint256 startTime;
uint256 endTime;
uint256 quantity;
address currency;
uint256 reservePricePerToken;
uint256 buyoutPricePerToken;
TokenType tokenType;
TransferType transferType;
uint64 rentalExpirationTimestamp;
ListingType listingType;
}
/**
* @notice The parameters an offeror sets when making an offer for NFTs.
*
* @param assetContract The contract of the NFTs for which the offer is being made.
* @param tokenId The tokenId of the NFT for which the offer is being made.
* @param quantity The quantity of NFTs wanted.
* @param currency The currency offered for the NFTs.
* @param totalPrice The total offer amount for the NFTs.
* @param expirationTimestamp The timestamp at and after which the offer cannot be accepted.
* @param transferType The type of transfer to be made : rent or sale. Rent is only possible if `assetContract` is ERC4907.
* @param rentalExpirationTimestamp The date after which the rental is expired. This is only applicable if `transferType` is `Rent`.
* @param referralAdditionalInformation Additional information for facilitating transactions, such as business referrer IDs or tracking codes.
*/
struct OfferParams {
address assetContract;
uint256 tokenId;
uint256 quantity;
address currency;
uint256 totalPrice;
uint256 expirationTimestamp;
TransferType transferType;
uint64 rentalExpirationTimestamp;
string referralAdditionalInformation;
}
/**
* @notice The information stored for the offer made.
*
* @param offerId The ID of the offer.
* @param tokenId The tokenId of the NFT for which the offer is being made.
* @param quantity The quantity of NFTs wanted.
* @param totalPrice The total offer amount for the NFTs.
* @param expirationTimestamp The timestamp at and after which the offer cannot be accepted.
* @param offeror The address of the offeror.
* @param assetContract The contract of the NFTs for which the offer is being made.
* @param currency The currency offered for the NFTs.
* @param tokenType The type of token (ERC-721 or ERC-1155) the offer is made for.
* @param transferType The type of transfer to be made : rent or sale. Rent is only possible if `assetContract` is ERC4907.
* @param rentalExpirationTimestamp The date after which the rental is expired. This is only applicable if `transferType` is `Rent`.
* @param status The status of the offer (created, completed, or cancelled).
* @param referralAdditionalInformation Additional information for facilitating transactions, such as business referrer IDs or tracking codes.
*/
struct Offer {
uint256 offerId;
uint256 tokenId;
uint256 quantity;
uint256 totalPrice;
uint256 expirationTimestamp;
address offeror;
address assetContract;
address currency;
TokenType tokenType;
TransferType transferType;
uint64 rentalExpirationTimestamp;
Status status;
string referralAdditionalInformation;
}
/// @dev Emitted when a new listing is created.
event ListingAdded(
uint256 indexed listingId,
address indexed assetContract,
address indexed lister,
Listing listing
);
/// @dev Emitted when the parameters of a listing are updated.
event ListingUpdated(
uint256 indexed listingId,
address indexed listingCreator,
ListingUpdateParameters params
);
/// @dev Emitted when a listing is cancelled.
event ListingRemoved(
uint256 indexed listingId,
address indexed listingCreator
);
/**
* @dev Emitted when a buyer buys from a direct listing
*/
event NewSale(
uint256 indexed listingId,
address indexed assetContract,
address indexed lister,
address buyer,
uint256 quantityBought,
uint256 totalPricePaid
);
/// @dev Emitted when a new bid is made in an auction.
event NewBid(
uint256 indexed listingId,
uint256 quantityWanted,
address indexed newBidder,
uint256 newPricePerToken,
address previousBidder,
uint256 refundBonus,
address currency,
uint256 newEndTime
);
/// @dev Emitted when an auction is closed.
event AuctionClosed(
uint256 indexed listingId,
address indexed closer,
bool indexed cancelled,
address auctionCreator,
address winningBidder
);
/// @dev Emitted when a new offer is created.
event NewOffer(
address indexed offeror,
uint256 indexed offerId,
address indexed assetContract,
Offer offer
);
/// @dev Emitted when an offer is cancelled.
event CancelledOffer(address indexed offeror, uint256 indexed offerId);
/// @dev Emitted when an offer is accepted.
event AcceptedOffer(
address indexed offeror,
uint256 indexed offerId,
address indexed assetContract,
uint256 tokenId,
address seller,
uint256 quantityBought,
uint256 totalPricePaid
);
/**
* @notice Lets a token owner list tokens (ERC 721 or ERC 1155) for sale in a direct listing, or an auction.
*
* @dev NFTs to list for sale in an auction are escrowed in Marketplace. For direct listings, the contract
* only checks whether the listing's creator owns and has approved Marketplace to transfer the NFTs to list.
*
* @param _params The parameters that govern the listing to be created.
*/
function createListing(ListingParameters memory _params) external;
/**
* @notice Lets a listing's creator edit the listing's parameters. A direct listing can be edited whenever.
* An auction listing cannot be edited after the auction has started.
*
* @param _listingId The uid of the listing to edit.
* @param _params The parameters that govern the listing to be updated
*/
function updateListing(
uint256 _listingId,
ListingUpdateParameters memory _params
) external;
/**
* @notice Lets a direct listing creator cancel their listing.
*
* @param _listingId The unique Id of the listing to cancel.
*/
function cancelDirectListing(uint256 _listingId) external;
/**
* @notice Lets someone from multiple items from direct listings (fixed prices)
*/
function buy(BuyParams calldata params) external payable;
/**
* @notice Lets someone make an bid in an auction.
*
* @dev Each (address, listing ID) pair maps to a single unique bid. So e.g. if a buyer makes
* makes two bids to the same direct listing, the last bid is counted as the buyer's
* bid to that listing.
*
* @param _listingId The unique ID of the listing to make an bid to.
* @param _pricePerToken The bid amount per token - includes fee for the previous bidder
* @param _bidder The account for whom the bid is made.
* @param _referralAdditionalInformation Additional information for facilitating transactions, such as business referrer IDs or tracking codes.
*/
function bid(
uint256 _listingId,
uint256 _pricePerToken,
address _bidder,
string memory _referralAdditionalInformation
) external payable;
/**
* @notice Lets any account close an auction.
* - The auction creator is sent the winning bid amount.
* - The winning bidder is sent the auctioned NFTs.
*
* @param _listingId The uid of the listing (the auction to close).
*/
function closeAuction(uint256 _listingId) external;
/**
* @notice Make an offer for NFTs (ERC-721 or ERC-1155)
*
* @param _params The parameters of an offer.
*
* @return offerId The unique integer ID assigned to the offer.
*/
function makeOffer(
OfferParams memory _params
) external returns (uint256 offerId);
/**
* @notice Cancel an offer.
*
* @param _offerId The ID of the offer to cancel.
*/
function cancelOffer(uint256 _offerId) external;
/**
* @notice Accept an offer.
*
* @param _offerId The ID of the offer to accept.
*/
function acceptOffer(uint256 _offerId) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the value of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {onERC1155Received} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `value` amount.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
*
* Requirements:
*
* - `ids` and `values` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Interface that must be implemented by smart contracts in order to receive
* ERC-1155 token transfers.
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @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`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
*/
function royaltyInfo(
uint256 tokenId,
uint256 salePrice
) external view returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IProtocolFee {
/// @notice Captures transaction details for a referral system, to track and reward contributions to the protocol treasury.
struct ReferralRevenue {
/// @notice The enabler, often a creator of sponsorship offers, shares revenue with the protocol.
address enabler;
/// @notice The spender, typically a sponsor, sends funds to the treasury.
address spender;
/// @notice Additional information for facilitating transactions, such as business referrer IDs or tracking codes.
string additionalInformation;
}
error CannotSendValueFromSender();
error ExternalCallError();
error InsufficientAllowance();
error InsufficientFunds();
error InvalidBps();
error ZeroAddress();
event CallWithProtocolFee(
address indexed origin,
address indexed currency,
uint256 feeAmount,
address enabler,
address spender,
string additionalInformation
);
event FeeUpdate(address recipient, uint96 bps);
function feeBps() external view returns (uint96);
function feeRecipient() external view returns (address payable);
function getFeeAmount(uint256 baseAmount) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IV3SwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// that may remain in the router after the swap.
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// that may remain in the router after the swap.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../interfaces/IProtocolFee.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IPeripheryPayments.sol";
import "@uniswap/swap-router-contracts/contracts/interfaces/IV3SwapRouter.sol";
interface WETH {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
interface UniV3SwapRouter is IV3SwapRouter, IPeripheryPayments {
function WETH9() external view returns (address);
}
/**
* @title ProtocolFee
* @author Anthony Gourraud
* @notice This contract incorporates protocol fee handling for transactions, enabling revenue generation for the protocol.
* It also supports a referral system to track and reward contributions from various ecosystem participants,
* including content creators, sponsors, and referrers. The contract ensures that every transaction contributing
* to the treasury is recorded to reward later accordingly, fostering a sustainable and growth-oriented ecosystem.
*/
abstract contract ProtocolFee is IProtocolFee, Context, ReentrancyGuard {
using SafeERC20 for IERC20;
/// @dev The max bps of the contract. So, 10_000 == 100 %
uint64 public constant MAX_BPS = 10_000;
UniV3SwapRouter public immutable swapRouter;
uint96 public feeBps;
address payable public feeRecipient;
/**
*
* @param _swapRouter The address of the Uniswap V3 SwapRouter
* @param _recipient The address to receive the protocol fee
* @param _bps The initial protocol fee in basis points (400 for 4%)
*/
constructor(
UniV3SwapRouter _swapRouter,
address payable _recipient,
uint96 _bps
) {
swapRouter = _swapRouter;
_updateProtocolFee(_recipient, _bps);
}
function getFeeAmount(uint256 baseAmount) public view returns (uint256) {
return Math.mulDiv(baseAmount, feeBps, MAX_BPS);
}
/**
* @notice function intended to execute calls to external contracts with protocol fee handling,
* with the capability to handle both native currency and ERC20 token payments.
* It also includes logic to swap native currency to ERC20 tokens via Uniswap V3
* if {msg.value} > 0 and the currency is not {address(0)}.
*
* @param target The address of the contract to call
* @param callData The calldata to be sent with the call
* @param currency The address of the ERC20 token for fee payment, or address(0) for native currency
* @param baseAmount Amount to send to the {target} contract. The protocol fee will be ADDED to this amount
* @param referral Referral information for the transaction. referral.spender will receive the refund if a swap occurs
* @return returnData The data returned by the external call
*
* @dev Calling this function with no nonReentrant modifier is dangerous as it allows reentrancy
*/
function _externalCallWithProtocolFee(
address target,
bytes memory callData,
address currency,
uint256 baseAmount,
ReferralRevenue memory referral
) internal returns (bytes memory) {
uint256 feeAmount = getFeeAmount(baseAmount);
uint256 totalAmount = feeAmount + baseAmount;
if (currency == address(0)) {
// Handling native currency
if (msg.value < totalAmount) {
revert InsufficientFunds();
}
} else {
// Handling ERC20 tokens
if (msg.value > 0) {
// Swap native currency to ERC20 if value is sent
_swapNativeToERC20(
currency,
totalAmount,
msg.value,
referral.spender
);
} else {
IERC20(currency).safeTransferFrom(
_msgSender(),
address(this),
totalAmount
);
}
// Approve the target to spend the received tokens
IERC20(currency).forceApprove(address(target), baseAmount);
}
_payFee(address(this), currency, feeAmount, target, referral);
/**
* @dev While this function ensures protocol fee handling and currency swapping,
* the actual outcome of the external call is dependent on the target contract's logic.
* This function does not enforce any constraints or expectations on the call's execution result,
* leaving the responsibility for handling the external call's effects to the caller or the target contract.
*/
uint256 value = currency == address(0) ? msg.value - feeAmount : 0;
bytes memory retData = Address.functionCallWithValue(
target,
callData,
value
);
return retData;
}
/**
* @notice Send a payment with ERC20 tokens or native currency
*
* @param from The address of the payment sender
* @param to The address of the recipient
* @param currency The address of the ERC20 token for fee payment, or address(0) for native currency
* @param feeAmount The amount to send
*/
function _pay(
address from,
address to,
address currency,
uint256 feeAmount
) internal {
if (feeAmount > 0) {
if (currency == address(0)) {
if (from != address(this)) {
revert CannotSendValueFromSender();
} else {
Address.sendValue(payable(to), feeAmount);
}
} else {
if (from == address(this)) {
IERC20(currency).safeTransfer(to, feeAmount);
} else {
IERC20(currency).safeTransferFrom(from, to, feeAmount);
}
}
}
}
/**
* @notice Pays the protocol fee to the fee recipient, tracking the transaction details for the referral system
*
* @param from The address of the transaction sender
* @param currency The address of the ERC20 token for fee payment, or address(0) for native currency
* @param feeAmount The amount to send to the protocol fee recipient
* @param origin To track the origin of the transaction
* @param referral To track the referral information for the transaction
*/
function _payFee(
address from,
address currency,
uint256 feeAmount,
address origin,
ReferralRevenue memory referral
) internal {
_pay(from, feeRecipient, currency, feeAmount);
emit CallWithProtocolFee(
origin,
currency,
feeAmount,
referral.enabler,
referral.spender,
referral.additionalInformation
);
}
/**
* @notice Swap to ERC20 tokens via Uniswap V3
*
* @param currency The address of the ERC20 token to swap to
* @param amount The amount of ERC20 tokens to get
* @param amountInMaximum The maximum amount of native currency to spend, expect to be msg.value
* @param recipientRefund The address to refund the remaining native currency.
*
* @dev If you use it in a loop, set `recipientRefund` to {address(0)} (refund to the contract), except on the last call
*
* @return amountOut The amount of ERC20 tokens received
*
*/
function _swapNativeToERC20(
address currency,
uint256 amount,
uint256 amountInMaximum,
address recipientRefund
) internal returns (uint256 amountOut, uint256 amountRefunded) {
address weth = swapRouter.WETH9();
uint256 balanceBeforeSwap = address(this).balance - amountInMaximum;
if (currency == weth) {
if (amountInMaximum < amount) {
revert InsufficientFunds();
}
amountOut = amount;
WETH(weth).deposit{value: amountOut}();
} else {
// perform the swap
IV3SwapRouter.ExactOutputSingleParams memory params = IV3SwapRouter
.ExactOutputSingleParams({
tokenIn: weth,
tokenOut: currency,
fee: 3000,
recipient: address(this),
amountOut: amount,
amountInMaximum: amountInMaximum,
sqrtPriceLimitX96: 0
});
amountOut = swapRouter.exactOutputSingle{value: amountInMaximum}(
params
);
// refund the remaining native currency
swapRouter.refundETH();
}
uint256 balanceAfterSwap = address(this).balance;
amountRefunded = balanceAfterSwap - balanceBeforeSwap;
address addrRefund = recipientRefund == address(0)
? address(this)
: recipientRefund;
if (amountRefunded > 0 && balanceAfterSwap > balanceBeforeSwap) {
Address.sendValue(payable(addrRefund), amountRefunded);
}
}
/**
* @notice Updates the protocol fee and recipient address
*
* @param _recipient The address to receive the protocol fee
* @param _bps The new protocol fee in basis points
*
* Emits a `FeeUpdate` event upon successful execution
*/
function _updateProtocolFee(
address payable _recipient,
uint96 _bps
) internal {
if (_recipient == address(0)) {
revert ZeroAddress();
}
if (_bps > MAX_BPS) {
revert InvalidBps();
}
feeBps = _bps;
feeRecipient = _recipient;
emit FeeUpdate(_recipient, _bps);
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
{
"compilationTarget": {
"contracts/DSponsorMarketplace.sol": "DSponsorMarketplace"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"forwarder","type":"address"},{"internalType":"address","name":"initialOwner","type":"address"},{"internalType":"contract UniV3SwapRouter","name":"_swapRouter","type":"address"},{"internalType":"address payable","name":"_recipient","type":"address"},{"internalType":"uint96","name":"_bps","type":"uint96"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"AuctionAlreadyStarted","type":"error"},{"inputs":[],"name":"AuctionStillActive","type":"error"},{"inputs":[],"name":"CannotBeZeroAddress","type":"error"},{"inputs":[],"name":"CannotSendValueFromSender","type":"error"},{"inputs":[],"name":"ExternalCallError","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"assetContract","type":"address"}],"name":"InsufficientAllowanceOrBalance","type":"error"},{"inputs":[],"name":"InsufficientFunds","type":"error"},{"inputs":[],"name":"InvalidBps","type":"error"},{"inputs":[],"name":"InvalidCurrency","type":"error"},{"inputs":[],"name":"InvalidPricingParameters","type":"error"},{"inputs":[],"name":"InvalidQuantity","type":"error"},{"inputs":[],"name":"InvalidRentalExpiration","type":"error"},{"inputs":[],"name":"InvalidTotalPrice","type":"error"},{"inputs":[],"name":"IsNotAuctionListing","type":"error"},{"inputs":[],"name":"IsNotDirectListing","type":"error"},{"inputs":[{"internalType":"uint256","name":"listingId","type":"uint256"}],"name":"ListingDoesNotExist","type":"error"},{"inputs":[],"name":"MathOverflowedMulDiv","type":"error"},{"inputs":[],"name":"NotERC4907Compliant","type":"error"},{"inputs":[],"name":"NotERC721OrERC1155","type":"error"},{"inputs":[{"internalType":"uint256","name":"offerId","type":"uint256"}],"name":"OfferIsNotActive","type":"error"},{"inputs":[],"name":"OutOfStock","type":"error"},{"inputs":[],"name":"OutOfValidityPeriod","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[],"name":"RefundExceedsBid","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"SenderIsNotOfferor","type":"error"},{"inputs":[],"name":"SenderIsNotTokenOwner","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"inputs":[],"name":"ZeroQuantity","type":"error"},{"inputs":[],"name":"isNotWinningBid","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"offeror","type":"address"},{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"address","name":"assetContract","type":"address"},{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"seller","type":"address"},{"indexed":false,"internalType":"uint256","name":"quantityBought","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalPricePaid","type":"uint256"}],"name":"AcceptedOffer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"listingId","type":"uint256"},{"indexed":true,"internalType":"address","name":"closer","type":"address"},{"indexed":true,"internalType":"bool","name":"cancelled","type":"bool"},{"indexed":false,"internalType":"address","name":"auctionCreator","type":"address"},{"indexed":false,"internalType":"address","name":"winningBidder","type":"address"}],"name":"AuctionClosed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"origin","type":"address"},{"indexed":true,"internalType":"address","name":"currency","type":"address"},{"indexed":false,"internalType":"uint256","name":"feeAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"enabler","type":"address"},{"indexed":false,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"string","name":"additionalInformation","type":"string"}],"name":"CallWithProtocolFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"offeror","type":"address"},{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"}],"name":"CancelledOffer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint96","name":"bps","type":"uint96"}],"name":"FeeUpdate","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"listingId","type":"uint256"},{"indexed":true,"internalType":"address","name":"assetContract","type":"address"},{"indexed":true,"internalType":"address","name":"lister","type":"address"},{"components":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"tokenOwner","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"reservePricePerToken","type":"uint256"},{"internalType":"uint256","name":"buyoutPricePerToken","type":"uint256"},{"internalType":"enum IDSponsorMarketplace.TokenType","name":"tokenType","type":"uint8"},{"internalType":"enum IDSponsorMarketplace.TransferType","name":"transferType","type":"uint8"},{"internalType":"uint64","name":"rentalExpirationTimestamp","type":"uint64"},{"internalType":"enum IDSponsorMarketplace.ListingType","name":"listingType","type":"uint8"}],"indexed":false,"internalType":"struct IDSponsorMarketplace.Listing","name":"listing","type":"tuple"}],"name":"ListingAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"listingId","type":"uint256"},{"indexed":true,"internalType":"address","name":"listingCreator","type":"address"}],"name":"ListingRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"listingId","type":"uint256"},{"indexed":true,"internalType":"address","name":"listingCreator","type":"address"},{"components":[{"internalType":"uint256","name":"quantityToList","type":"uint256"},{"internalType":"uint256","name":"reservePricePerToken","type":"uint256"},{"internalType":"uint256","name":"buyoutPricePerToken","type":"uint256"},{"internalType":"address","name":"currencyToAccept","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"secondsUntilEndTime","type":"uint256"},{"internalType":"uint64","name":"rentalExpirationTimestamp","type":"uint64"}],"indexed":false,"internalType":"struct IDSponsorMarketplace.ListingUpdateParameters","name":"params","type":"tuple"}],"name":"ListingUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"listingId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"quantityWanted","type":"uint256"},{"indexed":true,"internalType":"address","name":"newBidder","type":"address"},{"indexed":false,"internalType":"uint256","name":"newPricePerToken","type":"uint256"},{"indexed":false,"internalType":"address","name":"previousBidder","type":"address"},{"indexed":false,"internalType":"uint256","name":"refundBonus","type":"uint256"},{"indexed":false,"internalType":"address","name":"currency","type":"address"},{"indexed":false,"internalType":"uint256","name":"newEndTime","type":"uint256"}],"name":"NewBid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"offeror","type":"address"},{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"address","name":"assetContract","type":"address"},{"components":[{"internalType":"uint256","name":"offerId","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"uint256","name":"totalPrice","type":"uint256"},{"internalType":"uint256","name":"expirationTimestamp","type":"uint256"},{"internalType":"address","name":"offeror","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"enum IDSponsorMarketplace.TokenType","name":"tokenType","type":"uint8"},{"internalType":"enum IDSponsorMarketplace.TransferType","name":"transferType","type":"uint8"},{"internalType":"uint64","name":"rentalExpirationTimestamp","type":"uint64"},{"internalType":"enum IDSponsorMarketplace.Status","name":"status","type":"uint8"},{"internalType":"string","name":"referralAdditionalInformation","type":"string"}],"indexed":false,"internalType":"struct IDSponsorMarketplace.Offer","name":"offer","type":"tuple"}],"name":"NewOffer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"listingId","type":"uint256"},{"indexed":true,"internalType":"address","name":"assetContract","type":"address"},{"indexed":true,"internalType":"address","name":"lister","type":"address"},{"indexed":false,"internalType":"address","name":"buyer","type":"address"},{"indexed":false,"internalType":"uint256","name":"quantityBought","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalPricePaid","type":"uint256"}],"name":"NewSale","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"ADDITIONNAL_REFUND_PREVIOUS_BIDDER_BPS","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AUCTION_ENDTIME_BUFFER","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MAX_BPS","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MIN_AUCTION_INCREASE_BPS","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_offerId","type":"uint256"}],"name":"acceptOffer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_listingId","type":"uint256"},{"internalType":"uint256","name":"_pricePerToken","type":"uint256"},{"internalType":"address","name":"_bidder","type":"address"},{"internalType":"string","name":"_referralAdditionalInformation","type":"string"}],"name":"bid","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"buyFor","type":"address"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"string","name":"referralAdditionalInformation","type":"string"}],"internalType":"struct IDSponsorMarketplace.BuyParams","name":"buyParams","type":"tuple"}],"name":"buy","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_listingId","type":"uint256"}],"name":"cancelDirectListing","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_offerId","type":"uint256"}],"name":"cancelOffer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_listingId","type":"uint256"}],"name":"closeAuction","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"secondsUntilEndTime","type":"uint256"},{"internalType":"uint256","name":"quantityToList","type":"uint256"},{"internalType":"address","name":"currencyToAccept","type":"address"},{"internalType":"uint256","name":"reservePricePerToken","type":"uint256"},{"internalType":"uint256","name":"buyoutPricePerToken","type":"uint256"},{"internalType":"enum IDSponsorMarketplace.TransferType","name":"transferType","type":"uint8"},{"internalType":"uint64","name":"rentalExpirationTimestamp","type":"uint64"},{"internalType":"enum IDSponsorMarketplace.ListingType","name":"listingType","type":"uint8"}],"internalType":"struct IDSponsorMarketplace.ListingParameters","name":"_params","type":"tuple"}],"name":"createListing","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeBps","outputs":[{"internalType":"uint96","name":"","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeRecipient","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"baseAmount","type":"uint256"}],"name":"getFeeAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"forwarder","type":"address"}],"name":"isTrustedForwarder","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"listings","outputs":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"tokenOwner","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"endTime","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"reservePricePerToken","type":"uint256"},{"internalType":"uint256","name":"buyoutPricePerToken","type":"uint256"},{"internalType":"enum IDSponsorMarketplace.TokenType","name":"tokenType","type":"uint8"},{"internalType":"enum IDSponsorMarketplace.TransferType","name":"transferType","type":"uint8"},{"internalType":"uint64","name":"rentalExpirationTimestamp","type":"uint64"},{"internalType":"enum IDSponsorMarketplace.ListingType","name":"listingType","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"uint256","name":"totalPrice","type":"uint256"},{"internalType":"uint256","name":"expirationTimestamp","type":"uint256"},{"internalType":"enum IDSponsorMarketplace.TransferType","name":"transferType","type":"uint8"},{"internalType":"uint64","name":"rentalExpirationTimestamp","type":"uint64"},{"internalType":"string","name":"referralAdditionalInformation","type":"string"}],"internalType":"struct IDSponsorMarketplace.OfferParams","name":"_params","type":"tuple"}],"name":"makeOffer","outputs":[{"internalType":"uint256","name":"_offerId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"offers","outputs":[{"internalType":"uint256","name":"offerId","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"quantity","type":"uint256"},{"internalType":"uint256","name":"totalPrice","type":"uint256"},{"internalType":"uint256","name":"expirationTimestamp","type":"uint256"},{"internalType":"address","name":"offeror","type":"address"},{"internalType":"address","name":"assetContract","type":"address"},{"internalType":"address","name":"currency","type":"address"},{"internalType":"enum IDSponsorMarketplace.TokenType","name":"tokenType","type":"uint8"},{"internalType":"enum IDSponsorMarketplace.TransferType","name":"transferType","type":"uint8"},{"internalType":"uint64","name":"rentalExpirationTimestamp","type":"uint64"},{"internalType":"enum IDSponsorMarketplace.Status","name":"status","type":"uint8"},{"internalType":"string","name":"referralAdditionalInformation","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC1155Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"forwarder","type":"address"}],"name":"setTrustedForwarder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"swapRouter","outputs":[{"internalType":"contract UniV3SwapRouter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalListings","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalOffers","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"trustedForwarder","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_listingId","type":"uint256"},{"components":[{"internalType":"uint256","name":"quantityToList","type":"uint256"},{"internalType":"uint256","name":"reservePricePerToken","type":"uint256"},{"internalType":"uint256","name":"buyoutPricePerToken","type":"uint256"},{"internalType":"address","name":"currencyToAccept","type":"address"},{"internalType":"uint256","name":"startTime","type":"uint256"},{"internalType":"uint256","name":"secondsUntilEndTime","type":"uint256"},{"internalType":"uint64","name":"rentalExpirationTimestamp","type":"uint64"}],"internalType":"struct IDSponsorMarketplace.ListingUpdateParameters","name":"_params","type":"tuple"}],"name":"updateListing","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"winningBid","outputs":[{"internalType":"uint256","name":"listingId","type":"uint256"},{"internalType":"address","name":"bidder","type":"address"},{"internalType":"uint256","name":"pricePerToken","type":"uint256"},{"internalType":"string","name":"referralAdditionalInformation","type":"string"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]