Feature Tip: Add private address tag to any address under My Name Tag !
Source Code
Overview
ETH Balance
0 ETH
Eth Value
$0.00Latest 1 from a total of 1 transactions
| Transaction Hash |
Method
|
Block
|
From
|
|
To
|
||||
|---|---|---|---|---|---|---|---|---|---|
| Initialize | 24213915 | 18 days ago | IN | 0 ETH | 0.00000263 |
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions
Loading...
Loading
Contract Name:
SequentialCommitHandlerFacet
Compiler Version
v0.8.22+commit.4fc1097e
Optimization Enabled:
Yes with 100 runs
Other Settings:
shanghai EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.22;
import { IBosonSequentialCommitHandler } from "../../interfaces/handlers/IBosonSequentialCommitHandler.sol";
import { DiamondLib } from "../../diamond/DiamondLib.sol";
import { PriceDiscoveryBase } from "../bases/PriceDiscoveryBase.sol";
import "../../domain/BosonConstants.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
/**
* @title SequentialCommitHandlerFacet
*
* @notice Handles sequential commits.
*/
contract SequentialCommitHandlerFacet is IBosonSequentialCommitHandler, PriceDiscoveryBase {
using Address for address;
/**
* @notice
* For offers with native exchange token, it is expected that the price discovery contracts will
* operate with wrapped native token. Set the address of the wrapped native token in the constructor.
*
* @param _wNative - the address of the wrapped native token
*/
//solhint-disable-next-line
constructor(address _wNative) PriceDiscoveryBase(_wNative) {}
/**
* @notice Initializes facet.
* This function is callable only once.
*/
function initialize() public onlyUninitialized(type(IBosonSequentialCommitHandler).interfaceId) {
DiamondLib.addSupportedInterface(type(IBosonSequentialCommitHandler).interfaceId);
}
/**
* @notice Commits to an existing exchange. Price discovery is offloaded to external contract.
*
* Emits a BuyerCommitted event if successful.
* Transfers voucher to the buyer address.
*
* Reverts if:
* - The exchanges region of protocol is paused
* - The buyers region of protocol is paused
* - Buyer address is zero
* - Exchange does not exist
* - Exchange is not in Committed state
* - Voucher has expired
* - It is a bid order and:
* - Caller is not the voucher holder
* - Voucher owner did not approve protocol to transfer the voucher
* - Price received from price discovery is lower than the expected price
* - It is a ask order and:
* - Offer price is in native token and caller does not send enough
* - Offer price is in some ERC20 token and caller also sends native currency
* - Calling transferFrom on token fails for some reason (e.g. protocol is not approved to transfer)
* - Received ERC20 token amount differs from the expected value
* - Protocol does not receive the voucher
* - Transfer of voucher to the buyer fails for some reason (e.g. buyer is contract that doesn't accept voucher)
* - Reseller did not approve protocol to transfer exchange token in escrow
* - Call to price discovery contract fails
* - Protocol fee and royalties combined exceed the secondary price
* - Transfer of exchange token fails
*
* @param _buyer - the buyer's address (caller can commit on behalf of a buyer)
* @param _tokenId - the id of the token to commit to
* @param _priceDiscovery - the fully populated BosonTypes.PriceDiscovery struct
*/
function sequentialCommitToOffer(
address payable _buyer,
uint256 _tokenId,
PriceDiscovery calldata _priceDiscovery
) external payable exchangesNotPaused buyersNotPaused sequentialCommitNotPaused nonReentrant {
// Make sure buyer address is not zero address
if (_buyer == address(0)) revert InvalidAddress();
uint256 exchangeId = _tokenId & type(uint128).max;
// Exchange must exist
(Exchange storage exchange, Voucher storage voucher) = getValidExchange(exchangeId, ExchangeState.Committed);
// Make sure the voucher is still valid
if (block.timestamp > voucher.validUntilDate) revert VoucherHasExpired();
// Create a memory struct for sequential commit and populate it as we go
// This is done to avoid stack too deep error, while still keeping the number of SLOADs to a minimum
ExchangeCosts memory thisExchangeCost;
// Get current buyer address. This is actually the seller in sequential commit. Need to do it before voucher is transferred
address seller;
thisExchangeCost.resellerId = exchange.buyerId;
{
(, Buyer storage currentBuyer) = fetchBuyer(thisExchangeCost.resellerId);
seller = currentBuyer.wallet;
}
// Fetch offer
uint256 offerId = exchange.offerId;
(, Offer storage offer) = fetchOffer(offerId);
// First call price discovery and get actual price
// It might be lower than submitted for buy orders and higher for sell orders
thisExchangeCost.price = fulfilOrder(_tokenId, offer, _priceDiscovery, seller, _buyer);
// Get token address
address exchangeToken = offer.exchangeToken;
// Calculate the amount to be kept in escrow
uint256 additionalEscrowAmount;
uint256 immediatePayout;
{
// Get sequential commits for this exchange
ExchangeCosts[] storage exchangeCosts = protocolEntities().exchangeCosts[exchangeId];
{
// Calculate fees
thisExchangeCost.protocolFeeAmount = _getProtocolFee(exchangeToken, thisExchangeCost.price);
// Calculate royalties
{
RoyaltyInfo storage royaltyInfo;
(royaltyInfo, thisExchangeCost.royaltyInfoIndex, ) = fetchRoyalties(offerId, false);
thisExchangeCost.royaltyAmount =
(getTotalRoyaltyPercentage(royaltyInfo.bps) * thisExchangeCost.price) /
HUNDRED_PERCENT;
}
// Verify that fees and royalties are not higher than the price.
if (thisExchangeCost.protocolFeeAmount + thisExchangeCost.royaltyAmount > thisExchangeCost.price) {
revert FeeAmountTooHigh();
}
// Get the price, originally paid by the reseller
uint256 oldPrice;
unchecked {
uint256 len = exchangeCosts.length;
oldPrice = len == 0 ? offer.price : exchangeCosts[len - 1].price;
}
// Calculate the minimal amount to be kept in the escrow
unchecked {
additionalEscrowAmount =
thisExchangeCost.price -
Math.min(
oldPrice,
thisExchangeCost.price - thisExchangeCost.royaltyAmount - thisExchangeCost.protocolFeeAmount
);
}
// Store the exchange cost, so it can be used in calculations when releasing funds
exchangeCosts.push(thisExchangeCost);
}
// Make sure enough get escrowed
// Escrow amount is guaranteed to be less than or equal to price
unchecked {
immediatePayout = thisExchangeCost.price - additionalEscrowAmount;
}
// we have full proceeds in escrow. Keep minimal in, return the difference
if (thisExchangeCost.price > 0 && exchangeToken == address(0)) {
wNative.withdraw(thisExchangeCost.price);
}
if (immediatePayout > 0) {
transferFundsOut(exchangeToken, payable(seller), immediatePayout);
}
}
clearPriceDiscoveryStorage();
// Since exchange and voucher are passed by reference, they are updated
uint256 buyerId = exchange.buyerId;
address sender = _msgSender();
if (thisExchangeCost.price > 0) {
emit FundsDeposited(buyerId, sender, exchangeToken, thisExchangeCost.price);
emit FundsEncumbered(buyerId, exchangeToken, thisExchangeCost.price, sender);
}
if (immediatePayout > 0) {
emit FundsReleased(exchangeId, thisExchangeCost.resellerId, exchangeToken, immediatePayout, sender);
emit FundsWithdrawn(thisExchangeCost.resellerId, seller, exchangeToken, immediatePayout, sender);
}
emit BuyerCommitted(offerId, buyerId, exchangeId, exchange, voucher, sender);
// No need to update exchange detail. Most fields stay as they are, and buyerId was updated at the same time voucher is transferred
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @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 caller.
*
* 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: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @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 IERC165Upgradeable {
/**
* @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 v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @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 v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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, it is bubbled up by this
* function (like regular Solidity function calls).
*
* 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.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @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`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @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
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @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 up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (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; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
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.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 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.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
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 (rounding == Rounding.Up && 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 down.
*
* 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
import { IAccessControl } from "../interfaces/IAccessControl.sol";
import { IDiamondCut } from "../interfaces/diamond/IDiamondCut.sol";
/**
* @title DiamondLib
*
* @notice Provides Diamond storage slot and supported interface checks.
*
* @notice Based on Nick Mudge's gas-optimized diamond-2 reference,
* with modifications to support role-based access and management of
* supported interfaces. Also added copious code comments throughout.
*
* Reference Implementation : https://github.com/mudgen/diamond-2-hardhat
* EIP-2535 Diamond Standard : https://eips.ethereum.org/EIPS/eip-2535
*
* N.B. Facet management functions from original `DiamondLib` were refactored/extracted
* to JewelerLib, since business facets also use this library for access control and
* managing supported interfaces.
*
* @author Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
library DiamondLib {
bytes32 internal constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct DiamondStorage {
// Maps function selectors to the facets that execute the functions
// and maps the selectors to their position in the selectorSlots array.
// func selector => address facet, selector position
mapping(bytes4 => bytes32) facets;
// Array of slots of function selectors.
// Each slot holds 8 function selectors.
mapping(uint256 => bytes32) selectorSlots;
// The number of function selectors in selectorSlots
uint16 selectorCount;
// Used to query if a contract implement is an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// The Boson Protocol AccessController
IAccessControl accessController;
}
/**
* @notice Gets the Diamond storage slot.
*
* @return ds - Diamond storage slot cast to DiamondStorage
*/
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
/**
* @notice Adds a supported interface to the Diamond.
*
* @param _interfaceId - the interface to add
*/
function addSupportedInterface(bytes4 _interfaceId) internal {
// Get the DiamondStorage struct
DiamondStorage storage ds = diamondStorage();
// Flag the interfaces as supported
ds.supportedInterfaces[_interfaceId] = true;
}
/**
* @notice Removes a supported interface from the Diamond.
*
* @param _interfaceId - the interface to remove
*/
function removeSupportedInterface(bytes4 _interfaceId) internal {
// Get the DiamondStorage struct
DiamondStorage storage ds = diamondStorage();
// Flag the interfaces as unsupported
ds.supportedInterfaces[_interfaceId] = false;
}
/**
* @notice Checks if a specific interface is supported.
* Implementation of ERC-165 interface detection standard.
*
* @param _interfaceId - the sighash of the given interface
* @return - whether or not the interface is supported
*/
function supportsInterface(bytes4 _interfaceId) internal view returns (bool) {
// Get the DiamondStorage struct
DiamondStorage storage ds = diamondStorage();
// Return the value
return ds.supportedInterfaces[_interfaceId];
}
}import "./BosonTypes.sol";
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.22;
// Access Control Roles
bytes32 constant ADMIN = keccak256("ADMIN"); // Role Admin
bytes32 constant PAUSER = keccak256("PAUSER"); // Role for pausing the protocol
bytes32 constant PROTOCOL = keccak256("PROTOCOL"); // Role for facets of the ProtocolDiamond
bytes32 constant CLIENT = keccak256("CLIENT"); // Role for clients of the ProtocolDiamond
bytes32 constant UPGRADER = keccak256("UPGRADER"); // Role for performing contract and config upgrades
bytes32 constant FEE_COLLECTOR = keccak256("FEE_COLLECTOR"); // Role for collecting fees from the protocol
// Generic
uint256 constant HUNDRED_PERCENT = 10000; // 100% in basis points
uint256 constant PROTOCOL_ENTITY_ID = 0; // Entity ID for the protocol itself
uint256 constant VOIDED_OFFER_ID = type(uint256).max; // Offer ID for voided non-listed offers
// Pause Handler
uint256 constant ALL_REGIONS_MASK = (1 << (uint256(type(BosonTypes.PausableRegion).max) + 1)) - 1;
// Reentrancy guard
uint256 constant NOT_ENTERED = 1;
uint256 constant ENTERED = 2;
// Twin handler
uint256 constant SINGLE_TWIN_RESERVED_GAS = 160000;
uint256 constant MINIMAL_RESIDUAL_GAS = 230000;
// Config related
bytes32 constant VOUCHER_PROXY_SALT = keccak256(abi.encodePacked("BosonVoucherProxy"));
// Funds related
string constant NATIVE_CURRENCY = "Native currency";
string constant TOKEN_NAME_UNSPECIFIED = "Token name unavailable";
// EIP712Lib
string constant PROTOCOL_NAME = "Boson Protocol";
string constant PROTOCOL_VERSION = "V2";
bytes32 constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes("EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)")
);
uint256 constant SLOT_SIZE = 32; // Size of a slot in bytes, used for encoding and decoding
// BosonVoucher
string constant VOUCHER_NAME = "Boson Voucher (rNFT)";
string constant VOUCHER_SYMBOL = "BOSON_VOUCHER_RNFT";
// Meta Transactions - Error
string constant FUNCTION_CALL_NOT_SUCCESSFUL = "Function call not successful";
// External contracts errors
string constant OWNABLE_ZERO_ADDRESS = "Ownable: new owner is the zero address"; // exception message from OpenZeppelin Ownable
string constant ERC721_INVALID_TOKEN_ID = "ERC721: invalid token ID"; // exception message from OpenZeppelin ERC721
// Meta Transactions - Structs
bytes32 constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,address contractAddress,string functionName,bytes functionSignature)"
)
);
bytes32 constant OFFER_DETAILS_TYPEHASH = keccak256("MetaTxOfferDetails(address buyer,uint256 offerId)");
bytes32 constant META_TX_COMMIT_TO_OFFER_TYPEHASH = keccak256(
"MetaTxCommitToOffer(uint256 nonce,address from,address contractAddress,string functionName,MetaTxOfferDetails offerDetails)MetaTxOfferDetails(address buyer,uint256 offerId)"
);
bytes32 constant CONDITIONAL_OFFER_DETAILS_TYPEHASH = keccak256(
"MetaTxConditionalOfferDetails(address buyer,uint256 offerId,uint256 tokenId)"
);
bytes32 constant META_TX_COMMIT_TO_CONDITIONAL_OFFER_TYPEHASH = keccak256(
"MetaTxCommitToConditionalOffer(uint256 nonce,address from,address contractAddress,string functionName,MetaTxConditionalOfferDetails offerDetails)MetaTxConditionalOfferDetails(address buyer,uint256 offerId,uint256 tokenId)"
);
bytes32 constant EXCHANGE_DETAILS_TYPEHASH = keccak256("MetaTxExchangeDetails(uint256 exchangeId)");
bytes32 constant META_TX_EXCHANGE_TYPEHASH = keccak256(
"MetaTxExchange(uint256 nonce,address from,address contractAddress,string functionName,MetaTxExchangeDetails exchangeDetails)MetaTxExchangeDetails(uint256 exchangeId)"
);
bytes32 constant FUND_DETAILS_TYPEHASH = keccak256(
"MetaTxFundDetails(uint256 entityId,address[] tokenList,uint256[] tokenAmounts)"
);
bytes32 constant META_TX_FUNDS_TYPEHASH = keccak256(
"MetaTxFund(uint256 nonce,address from,address contractAddress,string functionName,MetaTxFundDetails fundDetails)MetaTxFundDetails(uint256 entityId,address[] tokenList,uint256[] tokenAmounts)"
);
bytes32 constant DISPUTE_RESOLUTION_DETAILS_TYPEHASH = keccak256(
"MetaTxDisputeResolutionDetails(uint256 exchangeId,uint256 buyerPercentBasisPoints,bytes signature)"
);
bytes32 constant META_TX_DISPUTE_RESOLUTIONS_TYPEHASH = keccak256(
"MetaTxDisputeResolution(uint256 nonce,address from,address contractAddress,string functionName,MetaTxDisputeResolutionDetails disputeResolutionDetails)MetaTxDisputeResolutionDetails(uint256 exchangeId,uint256 buyerPercentBasisPoints,bytes signature)"
);
// Function names
string constant COMMIT_TO_OFFER = "commitToOffer(address,uint256)";
string constant COMMIT_TO_CONDITIONAL_OFFER = "commitToConditionalOffer(address,uint256,uint256)";
string constant CANCEL_VOUCHER = "cancelVoucher(uint256)";
string constant REDEEM_VOUCHER = "redeemVoucher(uint256)";
string constant COMPLETE_EXCHANGE = "completeExchange(uint256)";
string constant WITHDRAW_FUNDS = "withdrawFunds(uint256,address[],uint256[])";
string constant RETRACT_DISPUTE = "retractDispute(uint256)";
string constant RAISE_DISPUTE = "raiseDispute(uint256)";
string constant ESCALATE_DISPUTE = "escalateDispute(uint256)";
string constant RESOLVE_DISPUTE = "resolveDispute(uint256,uint256,bytes)";// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.22;
import { BosonTypes } from "./BosonTypes.sol";
interface BosonErrors {
// Pause related
// Trying to unpause a protocol when it's not paused
error NotPaused();
// Whenever a region is paused, and a method from that region is called
error RegionPaused(BosonTypes.PausableRegion region);
// General
// Input parameter of type address is zero address
error InvalidAddress();
// Exchange or dispute is in different state than expected when certain action is called
error InvalidState();
// Two or more array parameters with different lengths
error ArrayLengthMismatch();
// Array elements that are not in ascending order (i.e arr[i-1] > arr[i])
error NonAscendingOrder();
// Called contract returned an unexpected value
error UnexpectedDataReturned(bytes data);
// Reentrancy guard
// Reentrancy guard is active and second call to protocol is made
error ReentrancyGuard();
// Protocol initialization related
// Trying to initialize the facet when it's already initialized
error AlreadyInitialized(); // ToDo consider adding the facet to the error message
// Initialization of some facet failed
error ProtocolInitializationFailed(); // ToDo consider adding the facet to the error message
// Trying to initialize the protocol with empty version
error VersionMustBeSet();
// Length of _addresses and _calldata arrays do not match
error AddressesAndCalldataLengthMismatch(); // ToDo consider reusing ArrayLengthMismatch
// The new protocol version is not subsequent to the current one
error WrongCurrentVersion();
// Initialization can be done only through proxy
error DirectInitializationNotAllowed();
// Initialization of v2.3.0 can be done only if not twin exists
error TwinsAlreadyExist();
// Access related
// ToDo consider having a single error, with a parameter for the role
// Caller is not authorized to call the method
error AccessDenied();
// Caller is not entitiy's assistant
error NotAssistant();
// Caller is not entitiy's admin
error NotAdmin();
// Caller is not entitiy's admin and assistant
error NotAdminAndAssistant();
// Caller is neither the buyer or the seller involved in the exchange
error NotBuyerOrSeller();
// Caller is not the owner of the voucher
error NotVoucherHolder();
// Caller is not the buyer
error NotBuyerWallet();
// Caller is not the agent
error NotAgentWallet();
// Caller is not dispute resolver assistant
error NotDisputeResolverAssistant();
// Caller is not the creator of the offer
error NotOfferCreator();
// Supplied clerk is not zero address
error ClerkDeprecated();
// Account-related
// Entity must be active
error MustBeActive();
// Seller's address cannot be already used in another seller
error SellerAddressMustBeUnique();
// Buyer's address cannot be already used in another buyer
error BuyerAddressMustBeUnique();
// DR's address cannot be already used in another DR
error DisputeResolverAddressMustBeUnique();
// Agent's address cannot be already used in another agent
error AgentAddressMustBeUnique();
// Seller does not exist
error NoSuchSeller();
// Buyer does not exist
error NoSuchBuyer();
// Dispute resolver does not exist
error NoSuchDisputeResolver();
// Agent does not exist
error NoSuchAgent();
// Entity does not exist
error NoSuchEntity();
// Buyer is involved in an non-finalized exchange
error WalletOwnsVouchers();
// Escalation period is not greater than zero or is more than the max allowed
error InvalidEscalationPeriod();
// Action would remove the last supported fee from the DR (must always have at least one)
error InexistentDisputeResolverFees();
// Trying to add a fee that already exists
error DuplicateDisputeResolverFees();
// Trying to remove a fee that does not exist
error DisputeResolverFeeNotFound();
// Trying to approve a seller that is already approved (list of sellers that DR will handle disputes for)
error SellerAlreadyApproved();
// Trying to assing a DR that had not approved the seller
error SellerNotApproved();
// Trying to add or removed 0 sellers
error InexistentAllowedSellersList();
// Custom auth token is not yet supported
error InvalidAuthTokenType();
// Seller must use either and address or auth token for authentication, but not both
error AdminOrAuthToken();
// A single auth token can only be used by one seller
error AuthTokenMustBeUnique();
// Sum of protocol and agent fee exceed the max allowed fee
error InvalidAgentFeePercentage();
// Trying to finalize the update, while it's not even started
error NoPendingUpdateForAccount();
// Only the account itself can finalize the update
error UnauthorizedCallerUpdate();
// Trying to update the account with the same values
error NoUpdateApplied();
// Creating a seller's collection failed
error CloneCreationFailed();
// Seller's salt is already used by another seller
error SellerSaltNotUnique();
// Offer related
// Offer does not exist
error NoSuchOffer();
// Offer parameters are invalid
error InvalidOffer();
// Collection index is invalid for the context
error InvalidCollectionIndex();
// Offer finishes in the past or it starts after it finishes
error InvalidOfferPeriod();
// Buyer cancellation penalty is higher than the item price
error InvalidOfferPenalty();
// New offer must be actiove
error OfferMustBeActive();
// Offer can be added to same group only once
error OfferMustBeUnique();
// Offer has been voided
error OfferHasBeenVoided();
// Current timestamp is higher than offer's expiry timestamp
error OfferHasExpired();
// Current timestamp is lower than offer's start timestamp
error OfferNotAvailable();
// Offer's quantity available is zero
error OfferSoldOut();
// Buyer is not allowed to commit to the offer (does not meet the token gating requirements)
error CannotCommit();
// Bundle cannot be created since exchganes for offer exist already
error ExchangeForOfferExists();
// Buyer-initiated offer cannot have seller-specific fields (sellerId, collectionIndex, royaltyInfo)
error InvalidBuyerOfferFields();
// Seller-initiated offer cannot have buyer-specific fields (buyerId, quantityAvailable)
error InvalidSellerOfferFields();
// Buyer cannot provide seller parameters when committing to an offer
error SellerParametersNotAllowed();
// Invalid offer creator value specified
error InvalidOfferCreator();
// Voucher must have either a fixed expiry or a fixed redeemable period, not both
error AmbiguousVoucherExpiry();
// Redemption period starts after it ends or it ends before offer itself expires
error InvalidRedemptionPeriod();
// Dispute period is less than minimal dispute period allowed
error InvalidDisputePeriod();
// Resolution period is not within the allowed range or it's being misconfigured (minimal > maximal)
error InvalidResolutionPeriod();
// Dispute resolver does not exist or is not active
error InvalidDisputeResolver();
// Quantity available is zero
error InvalidQuantityAvailable();
// Chose DR does not support the fees in the chosen exchange token
error DRUnsupportedFee();
// Sum of protocol and agent fee exceeds the max allowed fee
error AgentFeeAmountTooHigh();
// Sum of protocol and agent fee exceeds the seller defined max fee
error TotalFeeExceedsLimit();
// Collection does not exist
error NoSuchCollection();
// Royalty recipient is not allow listed for the seller
error InvalidRoyaltyRecipient();
// Total royality fee exceeds the max allowed
error InvalidRoyaltyPercentage();
// Specified royalty recipient already added
error RecipientNotUnique();
// Trying to access an out of bounds royalty recipient
error InvalidRoyaltyRecipientId();
// Array of royalty recipients is not sorted by id
error RoyaltyRecipientIdsNotSorted();
// Trying to remove the default recipient (treasury)
error CannotRemoveDefaultRecipient();
// Supplying too many Royalty info structs
error InvalidRoyaltyInfo();
// Trying to change the default recipient address (treasury)
error WrongDefaultRecipient();
// Price discovery offer has non zero price
error InvalidPriceDiscoveryPrice();
// Trying to set the same mutualizer as the existing one
error SameMutualizerAddress();
// Group related
// Group does not exist
error NoSuchGroup();
// Offer is not in a group
error OfferNotInGroup();
// Group remains the same
error NothingUpdated();
// There is a logical error in the group's condition parameters or it's not supported yet
error InvalidConditionParameters();
// Group does not have a condition
error GroupHasNoCondition();
// Group has a condition
error GroupHasCondition();
// User exhaused the number of commits allowed for the group
error MaxCommitsReached();
// The supplied token id is outside the condition's range
error TokenIdNotInConditionRange();
// ERC20 and ERC721 require zero token id
error InvalidTokenId();
// Exchange related
// Exchange does not exist
error NoSuchExchange();
// Exchange cannot be completed yet
error DisputePeriodNotElapsed();
// Current timestamp is outside the voucher's redeemable period
error VoucherNotRedeemable();
// New expiration date is earlier than existing expiration date
error VoucherExtensionNotValid();
// Voucher cannot be expired yet
error VoucherStillValid();
// Voucher has expired and cannot be transferred anymore
error VoucherHasExpired();
// Exchange has not been finalized yet
error ExchangeIsNotInAFinalState();
// Exchange with the same id already exists
error ExchangeAlreadyExists();
// Range length is 0, is more than quantity available or it would cause an overflow
error InvalidRangeLength();
// Exchange is being finalized into an invalid state
error InvalidTargeExchangeState();
// Twin related
// Twin does not exist
error NoSuchTwin();
// Seller did not approve the twin transfer
error NoTransferApproved();
// Twin transfer failed
error TwinTransferUnsuccessful();
// Token address is 0 or it does not implement the required interface
error UnsupportedToken();
// Twin cannot be removed if it's in a bundle
error BundleForTwinExists();
// Supply available is zero
error InvalidSupplyAvailable();
// Twin is Fungible or Multitoken and amount was set
error InvalidAmount();
// Twin is NonFungible and amount was not set
error InvalidTwinProperty(); // ToDo consider replacing with InvalidAmount
// Token range overlap with another, starting token id is too high or end of range would overflow
error InvalidTwinTokenRange();
// Token does not support IERC721 interface
error InvalidTokenAddress();
// Bundle related
// Bundle does not exist
error NoSuchBundle();
// Twin is not in a bundle
error TwinNotInBundle();
// Offer is not in a bundle
error OfferNotInBundle();
// Offer can appear in a bundle only once
error BundleOfferMustBeUnique();
// Twin can appear in a bundle only once
error BundleTwinMustBeUnique();
// Twin supply does not covver all offers in the bundle
error InsufficientTwinSupplyToCoverBundleOffers();
// Bundle cannot be created without an offer or a twin
error BundleRequiresAtLeastOneTwinAndOneOffer();
// Funds related
// Native token must be represented with zero address
error NativeWrongAddress();
// Amount sent along (msg.value) does not match the expected amount
error NativeWrongAmount();
// Token list lenght does not match the amount list length
error TokenAmountMismatch(); // ToDo consider replacing with ArrayLengthMismatch
// Token list is empty
error NothingToWithdraw();
// Call is not allowed to transfer the funds
error NotAuthorized();
// Token transfer failed
error TokenTransferFailed();
// Received amount does not match the expected amount
error InsufficientValueReceived();
// Seller's pool does not have enough funds to encumber
error InsufficientAvailableFunds();
// Native token was sent when ERC20 was expected
error NativeNotAllowed();
// Trying to deposit zero amount
error ZeroDepositNotAllowed();
// DR Fee related
// DR fee mutualizer cannot provide coverage for the fee
error DRFeeMutualizerCannotProvideCoverage();
// Meta-Transactions related
// Meta-transaction nonce is invalid
error NonceUsedAlready();
// Function signature does not match it's name
error InvalidFunctionName();
// Signature has invalid parameters
error InvalidSignature();
// Function is not allowed to be executed as a meta-transaction
error FunctionNotAllowlisted();
// Signer does not match the expected one or ERC1271 signature is not valid
error SignatureValidationFailed();
// Dispute related
// Dispute cannot be raised since the period to do it has elapsed
error DisputePeriodHasElapsed();
// Mutualizer address does not implement the required interface
error UnsupportedMutualizer();
// Dispute cannot be resolved anymore and must be finalized with expireDispute
error DisputeHasExpired();
// Buyer gets more than 100% of the total pot
error InvalidBuyerPercent();
// Dispute is still valid and cannot be expired yet
error DisputeStillValid();
// New dispute timeout is earlier than existing dispute timeout
error InvalidDisputeTimeout();
// Absolute zero offers cannot be escalated
error EscalationNotAllowed();
// Dispute is being finalized into an invalid state
error InvalidTargeDisputeState();
// Config related
// Percentage exceeds 100%
error InvalidFeePercentage();
// Zero config value is not allowed
error ValueZeroNotAllowed();
// BosonVoucher
// Trying to issue an voucher that is in a reseverd range
error ExchangeIdInReservedRange();
// Trying to premint vouchers for an offer that does not have a reserved range
error NoReservedRangeForOffer();
// Trying to reserve a range that is already reserved
error OfferRangeAlreadyReserved();
// Range start at 0 is not allowed
error InvalidRangeStart();
// Amount to premint exceeds the range length
error InvalidAmountToMint();
// Trying to silent mint vouchers not belonging to the range owner
error NoSilentMintAllowed();
// Trying to premint the voucher of already expired offer
error OfferExpiredOrVoided();
// Trying to burn preminted vouchers of still valid offer
error OfferStillValid();
// Trying to burn more vouchers than available
error AmountExceedsRangeOrNothingToBurn();
// Royalty fee exceeds the max allowed
error InvalidRoyaltyFee();
// Trying to assign the premined vouchers to the address that is neither the contract owner nor the contract itself
error InvalidToAddress();
// Call to an external contract was not successful
error ExternalCallFailed();
// Trying to interact with external contract in a way that could result in transferring assets from the contract
error InteractionNotAllowed();
// Price discovery related
// Price discovery returned a price that does not match the expected one
error PriceMismatch();
// Token id is mandatory for bid orders and wrappers
error TokenIdMandatory();
// Incoming token id does not match the expected one
error TokenIdMismatch();
// Using price discovery for non-price discovery offer or using ordinary commit for price discovery offer
error InvalidPriceType();
// Missing price discovery contract address or data
error InvalidPriceDiscovery();
// Trying to set incoming voucher when it's already set, indicating reentrancy
error IncomingVoucherAlreadySet();
// Conduit address must be zero ()
error InvalidConduitAddress();
// Protocol does not know what token id to use
error TokenIdNotSet();
// Transferring a preminted voucher to wrong recipient
error VoucherTransferNotAllowed();
// Price discovery contract returned a negative price
error NegativePriceNotAllowed();
// Price discovery did not send the voucher to the protocol
error VoucherNotReceived();
// Price discovery did not send the voucher from the protocol
error VoucherNotTransferred();
// Either token with wrong id received or wrong voucher contract made the transfer
error UnexpectedERC721Received();
// Royalty fee exceeds the price
error FeeAmountTooHigh();
// Price does not cover the cancellation penalty
error PriceDoesNotCoverPenalty();
// Fee Table related
// Thrown if asset is not supported in feeTable feature.
error FeeTableAssetNotSupported();
}// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.22;
/**
* @title BosonTypes
*
* @notice Enums and structs used by the Boson Protocol contract ecosystem.
*/
contract BosonTypes {
enum PausableRegion {
Offers,
Twins,
Bundles,
Groups,
Sellers,
Buyers,
DisputeResolvers,
Agents,
Exchanges,
Disputes,
Funds,
Orchestration,
MetaTransaction,
PriceDiscovery,
SequentialCommit
}
enum EvaluationMethod {
None, // None should always be at index 0. Never change this value.
Threshold,
SpecificToken
}
enum GatingType {
PerAddress,
PerTokenId
}
enum ExchangeState {
Committed,
Revoked,
Canceled,
Redeemed,
Completed,
Disputed
}
enum DisputeState {
Resolving,
Retracted,
Resolved,
Escalated,
Decided,
Refused
}
enum TokenType {
FungibleToken,
NonFungibleToken,
MultiToken
} // ERC20, ERC721, ERC1155
enum MetaTxInputType {
Generic,
CommitToOffer,
Exchange,
Funds,
CommitToConditionalOffer,
ResolveDispute
}
enum AuthTokenType {
None,
Custom, // For future use
Lens,
ENS
}
enum SellerUpdateFields {
Admin,
Assistant,
Clerk, // Deprecated.
AuthToken
}
enum DisputeResolverUpdateFields {
Admin,
Assistant,
Clerk // Deprecated.
}
enum PriceType {
Static, // Default should always be at index 0. Never change this value.
Discovery
}
enum OfferCreator {
Seller, // Default should always be at index 0. Never change this value.
Buyer
}
struct AuthToken {
uint256 tokenId;
AuthTokenType tokenType;
}
struct Seller {
uint256 id;
address assistant;
address admin;
address clerk; // Deprecated. Kept for backwards compatibility.
address payable treasury;
bool active;
string metadataUri;
}
struct Buyer {
uint256 id;
address payable wallet;
bool active;
}
struct RoyaltyRecipient {
uint256 id;
address payable wallet;
}
struct DisputeResolver {
uint256 id;
uint256 escalationResponsePeriod;
address assistant;
address admin;
address clerk; // Deprecated. Kept for backwards compatibility.
address payable treasury;
string metadataUri;
bool active;
}
struct DisputeResolverFee {
address tokenAddress;
string tokenName;
uint256 feeAmount;
}
struct Agent {
uint256 id;
uint256 feePercentage;
address payable wallet;
bool active;
}
struct DisputeResolutionTerms {
uint256 disputeResolverId;
uint256 escalationResponsePeriod;
uint256 feeAmount;
uint256 buyerEscalationDeposit;
address payable mutualizerAddress; // Address of the DR fee mutualizer
}
struct Offer {
uint256 id;
uint256 sellerId;
uint256 price;
uint256 sellerDeposit;
uint256 buyerCancelPenalty;
uint256 quantityAvailable;
address exchangeToken;
PriceType priceType;
OfferCreator creator;
string metadataUri;
string metadataHash;
bool voided;
uint256 collectionIndex;
RoyaltyInfo[] royaltyInfo;
uint256 buyerId; // For buyer-created offers, stores the buyer who created the offer
}
struct DRParameters {
uint256 disputeResolverId;
address payable mutualizerAddress;
}
struct OfferDates {
uint256 validFrom;
uint256 validUntil;
uint256 voucherRedeemableFrom;
uint256 voucherRedeemableUntil;
}
struct OfferDurations {
uint256 disputePeriod;
uint256 voucherValid;
uint256 resolutionPeriod;
}
struct FullOffer {
Offer offer;
OfferDates offerDates;
OfferDurations offerDurations;
DRParameters drParameters;
Condition condition;
uint256 agentId;
uint256 feeLimit;
bool useDepositedFunds;
}
struct Group {
uint256 id;
uint256 sellerId;
uint256[] offerIds;
}
struct Condition {
EvaluationMethod method;
TokenType tokenType;
address tokenAddress;
GatingType gating; // added in v2.3.0. All conditions created before that have a default value of "PerAddress"
uint256 minTokenId;
uint256 threshold;
uint256 maxCommits;
uint256 maxTokenId;
}
struct Exchange {
uint256 id;
uint256 offerId;
uint256 buyerId;
uint256 finalizedDate;
ExchangeState state;
address payable mutualizerAddress;
}
struct ExchangeCosts {
uint256 resellerId;
uint256 price;
uint256 protocolFeeAmount;
uint256 royaltyAmount;
uint256 royaltyInfoIndex;
}
struct Voucher {
uint256 committedDate;
uint256 validUntilDate;
uint256 redeemedDate;
bool expired;
}
struct Dispute {
uint256 exchangeId;
uint256 buyerPercent;
DisputeState state;
}
struct DisputeDates {
uint256 disputed;
uint256 escalated;
uint256 finalized;
uint256 timeout;
}
struct Receipt {
uint256 exchangeId;
uint256 offerId;
uint256 buyerId;
uint256 sellerId;
uint256 price;
uint256 sellerDeposit;
uint256 buyerCancelPenalty;
OfferFees offerFees;
uint256 agentId;
address exchangeToken;
uint256 finalizedDate;
Condition condition;
uint256 committedDate;
uint256 redeemedDate;
bool voucherExpired;
uint256 disputeResolverId;
uint256 disputedDate;
uint256 escalatedDate;
DisputeState disputeState;
TwinReceipt[] twinReceipts;
}
struct TokenRange {
uint256 start;
uint256 end;
uint256 twinId;
}
struct Twin {
uint256 id;
uint256 sellerId;
uint256 amount; // ERC1155 / ERC20 (amount to be transferred to each buyer on redemption)
uint256 supplyAvailable; // all
uint256 tokenId; // ERC1155 / ERC721 (must be initialized with the initial pointer position of the ERC721 ids available range)
address tokenAddress; // all
TokenType tokenType;
}
struct TwinReceipt {
uint256 twinId;
uint256 tokenId; // only for ERC721 and ERC1155
uint256 amount; // only for ERC1155 and ERC20
address tokenAddress;
TokenType tokenType;
}
struct Bundle {
uint256 id;
uint256 sellerId;
uint256[] offerIds;
uint256[] twinIds;
}
struct Funds {
address tokenAddress;
string tokenName;
uint256 availableAmount;
}
struct MetaTransaction {
uint256 nonce;
address from;
address contractAddress;
string functionName;
bytes functionSignature;
}
struct HashInfo {
bytes32 typeHash;
function(bytes memory) internal pure returns (bytes32) hashFunction;
}
struct OfferFees {
uint256 protocolFee;
uint256 agentFee;
}
struct VoucherInitValues {
string contractURI;
uint256 royaltyPercentage;
bytes32 collectionSalt;
}
struct Collection {
address collectionAddress;
string externalId;
}
struct PriceDiscovery {
uint256 price;
Side side;
address priceDiscoveryContract;
address conduit;
bytes priceDiscoveryData;
}
enum Side {
Ask,
Bid,
Wrapper // Side is not relevant from the protocol perspective
}
struct RoyaltyInfo {
address payable[] recipients;
uint256[] bps;
}
struct RoyaltyRecipientInfo {
address payable wallet;
uint256 minRoyaltyPercentage;
}
struct PremintParameters {
uint256 reservedRangeLength;
address to;
}
struct Payoff {
uint256 seller;
uint256 buyer;
uint256 protocol;
uint256 agent;
uint256 disputeResolver;
uint256 mutualizer;
}
struct SellerOfferParams {
uint256 collectionIndex;
RoyaltyInfo royaltyInfo;
address payable mutualizerAddress;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
import { IBosonVoucher } from "./IBosonVoucher.sol";
import { IERC721Receiver } from "../IERC721Receiver.sol";
import { BosonTypes } from "../../domain/BosonTypes.sol";
/**
* @title BosonPriceDiscovery
*
* @notice This is the interface for the Boson Price Discovery contract.
*
* The ERC-165 identifier for this interface is: 0x8bcce417
*/
interface IBosonPriceDiscovery is IERC721Receiver {
/**
* @notice Fulfils an ask order on external contract.
*
* Reverts if:
* - Call to price discovery contract fails
* - The implied price is negative
* - Any external calls to erc20 contract fail
*
* @param _exchangeToken - the address of the exchange contract
* @param _priceDiscovery - the fully populated BosonTypes.PriceDiscovery struct
* @param _bosonVoucher - the boson voucher contract
* @param _msgSender - the address of the caller, as seen in boson protocol
* @return actualPrice - the actual price of the order
*/
function fulfilAskOrder(
address _exchangeToken,
BosonTypes.PriceDiscovery calldata _priceDiscovery,
IBosonVoucher _bosonVoucher,
address payable _msgSender
) external returns (uint256 actualPrice);
/**
* @notice Fulfils a bid order on external contract.
*
* Reverts if:
* - Call to price discovery contract fails
* - Protocol balance change after price discovery call is lower than the expected price
* - This contract is still owner of the voucher
* - Token id sent to buyer and token id set by the caller don't match
* - The implied price is negative
* - Any external calls to erc20 contract fail
*
* @param _tokenId - the id of the token
* @param _exchangeToken - the address of the exchange token
* @param _priceDiscovery - the fully populated BosonTypes.PriceDiscovery struct
* @param _seller - the seller's address
* @param _bosonVoucher - the boson voucher contract
* @return actualPrice - the actual price of the order
*/
function fulfilBidOrder(
uint256 _tokenId,
address _exchangeToken,
BosonTypes.PriceDiscovery calldata _priceDiscovery,
address _seller,
IBosonVoucher _bosonVoucher
) external payable returns (uint256 actualPrice);
/**
* @notice Call `unwrap` (or equivalent) function on the price discovery contract.
*
* Reverts if:
* - Protocol balance doesn't increase by the expected amount.
* - Token id sent to buyer and token id set by the caller don't match
* - The wrapper contract sends back the native currency
* - The implied price is negative
*
* @param _exchangeToken - the address of the exchange contract
* @param _priceDiscovery - the fully populated BosonTypes.PriceDiscovery struct
* @return actualPrice - the actual price of the order
*/
function handleWrapper(
address _exchangeToken,
BosonTypes.PriceDiscovery calldata _priceDiscovery
) external payable returns (uint256 actualPrice);
}// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.22;
import { IERC721Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import {
IERC721MetadataUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol";
import {
IERC721ReceiverUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
/**
* @title IBosonVoucher
*
* @notice This is the interface for the Boson Protocol ERC-721 Voucher contract.
*
* The ERC-165 identifier for this interface is: 0x6a474d2c
*/
interface IBosonVoucher is IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721ReceiverUpgradeable {
event ContractURIChanged(string contractURI);
event VoucherInitialized(uint256 indexed sellerId, string indexed contractURI);
event RangeReserved(uint256 indexed offerId, Range range);
event VouchersPreMinted(uint256 indexed offerId, uint256 startId, uint256 endId);
// Describe a reserved range of token ids
struct Range {
uint256 start; // First token id of range
uint256 length; // Length of range
uint256 minted; // Amount pre-minted so far
uint256 lastBurnedTokenId; // Last burned token id
address owner; // The range owner
}
/**
* @notice Issues a voucher to a buyer.
*
* Minted voucher supply is sent to the buyer.
* Caller must have PROTOCOL role.
*
* @param _tokenId - voucher token id corresponds to <<uint128(offerId)>>.<<uint128(exchangeId)>>
* @param _buyer - the buyer address
*/
function issueVoucher(uint256 _tokenId, address _buyer) external;
/**
* @notice Burns a voucher.
*
* Caller must have PROTOCOL role.
*
* @param _tokenId - voucher token id corresponds to <<uint128(offerId)>>.<<uint128(exchangeId)>>
*/
function burnVoucher(uint256 _tokenId) external;
/**
* @notice Gets the seller id.
*
* @return the id for the Voucher seller
*/
function getSellerId() external view returns (uint256);
/**
* @notice Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the protocol. Change is done by calling `updateSeller` on the protocol.
*
* @param newOwner - the address to which ownership of the voucher contract will be transferred
*/
function transferOwnership(address newOwner) external;
/**
* @notice Returns storefront-level metadata used by OpenSea.
*
* @return Contract metadata URI
*/
function contractURI() external view returns (string memory);
/**
* @notice Sets new contract URI.
* Can only be called by the owner or during the initialization.
*
* @param _newContractURI - new contract metadata URI
*/
function setContractURI(string calldata _newContractURI) external;
/**
* @notice Provides royalty info.
* Called with the sale price to determine how much royalty is owed and to whom.
*
* @param _tokenId - the voucher queried for royalty information
* @param _salePrice - the sale price of the voucher specified by _tokenId
*
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for the given sale price
*/
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view returns (address receiver, uint256 royaltyAmount);
/**
* @notice Reserves a range of vouchers to be associated with an offer
*
* Must happen prior to calling preMint
* Caller must have PROTOCOL role.
*
* Reverts if:
* - Start id is not greater than zero for the first range
* - Start id is not greater than the end id of the previous range for subsequent ranges
* - Range length is zero
* - Range length is too large, i.e., would cause an overflow
* - Offer id is already associated with a range
* - _to is not the contract address or the contract owner
*
* @param _offerId - the id of the offer
* @param _start - the first id of the token range
* @param _length - the length of the range
* @param _to - the address to send the pre-minted vouchers to (contract address or contract owner)
*/
function reserveRange(uint256 _offerId, uint256 _start, uint256 _length, address _to) external;
/**
* @notice Pre-mints all or part of an offer's reserved vouchers.
*
* For small offer quantities, this method may only need to be
* called once.
*
* But, if the range is large, e.g., 10k vouchers, block gas limit
* could cause the transaction to fail. Thus, in order to support
* a batched approach to pre-minting an offer's vouchers,
* this method can be called multiple times, until the whole
* range is minted.
*
* A benefit to the batched approach is that the entire reserved
* range for an offer need not be pre-minted at one time. A seller
* could just mint batches periodically, controlling the amount
* that are available on the market at any given time, e.g.,
* creating a pre-minted offer with a validity period of one year,
* causing the token range to be reserved, but only pre-minting
* a certain amount monthly.
*
* Caller must be contract owner (seller assistant address).
*
* Reverts if:
* - Offer id is not associated with a range
* - Amount to mint is more than remaining un-minted in range
* - Too many to mint in a single transaction, given current block gas limit
*
* @param _offerId - the id of the offer
* @param _amount - the amount to mint
*/
function preMint(uint256 _offerId, uint256 _amount) external;
/**
* @notice Burn all or part of an offer's preminted vouchers.
* If offer expires or it's voided, the seller can burn the preminted vouchers that were not transferred yet.
* This way they will not show in seller's wallet and marketplaces anymore.
*
* For small offer quantities, this method may only need to be
* called once.
*
* But, if the range is large, e.g., 10k vouchers, block gas limit
* could cause the transaction to fail. Thus, in order to support
* a batched approach to pre-minting an offer's vouchers,
* this method can be called multiple times, until the whole
* range is burned.
*
* Caller must be contract owner (seller assistant address).
*
* Reverts if:
* - Offer id is not associated with a range
* - Offer is not expired or voided
* - There is nothing to burn
*
* @param _offerId - the id of the offer
* @param _amount - amount to burn
*/
function burnPremintedVouchers(uint256 _offerId, uint256 _amount) external;
/**
* @notice Gets the number of vouchers available to be pre-minted for an offer.
*
* @param _offerId - the id of the offer
* @return count - the count of vouchers in reserved range available to be pre-minted
*/
function getAvailablePreMints(uint256 _offerId) external view returns (uint256 count);
/**
* @notice Gets the range for an offer.
*
* @param _offerId - the id of the offer
* @return range - range struct with information about range start, length and already minted tokens
*/
function getRangeByOfferId(uint256 _offerId) external view returns (Range memory range);
/**
* @notice Make a call to an external contract.
*
* Reverts if:
* - _to is zero address
* - call to external contract fails
* - caller is not the owner
* - _to is a contract that represents some assets (all contracts that implement `balanceOf` method, including ERC20 and ERC721)
*
* @param _to - address of the contract to call
* @param _data - data to pass to the external contract
* @return result - result of the call
*/
function callExternalContract(address _to, bytes memory _data) external payable returns (bytes memory);
/** @notice Set approval for all to the vouchers owned by this contract
*
* Reverts if:
* - _operator is zero address
* - caller is not the owner
* - _operator is this contract
*
* @param _operator - address of the operator to set approval for
* @param _approved - true to approve the operator in question, false to revoke approval
*/
function setApprovalForAllToContract(address _operator, bool _approved) external;
/**
* @notice Withdraw funds from the contract to the protocol seller pool
*
* @param _tokenList - list of tokens to withdraw, including native token (address(0))
*/
function withdrawToProtocol(address[] calldata _tokenList) external;
}// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.22;
import { IERC165 } from "../IERC165.sol";
/**
* @title IDRFeeMutualizer
* @notice Interface for dispute resolver fee mutualization
*
* The ERC-165 identifier for this interface is: 0xe627eff4
*/
interface IDRFeeMutualizer is IERC165 {
/**
* @notice Checks if a seller is covered for a specific DR fee
* @param _sellerId The seller ID
* @param _feeAmount The fee amount to cover
* @param _tokenAddress The token address (address(0) for native currency)
* @param _disputeResolverId The dispute resolver ID (0 for universal agreement covering all dispute resolvers)
* @return bool True if the seller is covered, false otherwise
* @dev Checks for both specific dispute resolver agreements and universal agreements (disputeResolverId = 0).
*/
function isSellerCovered(
uint256 _sellerId,
uint256 _feeAmount,
address _tokenAddress,
uint256 _disputeResolverId
) external view returns (bool);
/**
* @notice Requests a DR fee for a seller
* @param _sellerId The seller ID
* @param _feeAmount The fee amount to cover
* @param _tokenAddress The token address (address(0) for native currency)
* @param _exchangeId The exchange ID
* @param _disputeResolverId The dispute resolver ID (0 for universal agreement)
* @return success True if the request was successful, false otherwise
* @dev Only callable by the Boson protocol. Returns false if seller is not covered.
*
* Emits a {DRFeeProvided} event if successful.
*
* Reverts if:
* - Caller is not the Boson protocol
* - feeAmount is 0
* - Pool balance is insufficient
* - ERC20 or native currency transfer fails
*/
function requestDRFee(
uint256 _sellerId,
uint256 _feeAmount,
address _tokenAddress,
uint256 _exchangeId,
uint256 _disputeResolverId
) external returns (bool success);
/**
* @notice Notifies the mutualizer that the exchange has been finalized and any unused fee can be returned
* @param _exchangeId The exchange ID
* @param _feeAmount The amount being returned (0 means protocol kept all fees)
* @dev Only callable by the Boson protocol. For native currency, token is wrapped and must be transferred as ERC20.
*
* Emits a {DRFeeReturned} event.
*
* Reverts if:
* - Caller is not the Boson protocol
* - exchangeId is not found
* - token transfer fails
*/
function finalizeExchange(uint256 _exchangeId, uint256 _feeAmount) external;
}// SPDX-License-Identifier: MIT pragma solidity 0.8.22; /** * @title IDiamondCut * * @notice Manages Diamond Facets. * * Reference Implementation : https://github.com/mudgen/diamond-2-hardhat * EIP-2535 Diamond Standard : https://eips.ethereum.org/EIPS/eip-2535 * * The ERC-165 identifier for this interface is: 0x1f931c1c * * @author Nick Mudge <[email protected]> (https://twitter.com/mudgen) */ interface IDiamondCut { event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); enum FacetCutAction { Add, Replace, Remove } struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /** * @notice Cuts facets of the Diamond. * * Adds/replaces/removes any number of function selectors. * * If populated, _calldata is executed with delegatecall on _init * * Reverts if caller does not have UPGRADER role * * @param _facetCuts - contains the facet addresses and function selectors * @param _init - the address of the contract or facet to execute _calldata * @param _calldata - a function call, including function selector and arguments */ function diamondCut(FacetCut[] calldata _facetCuts, address _init, bytes calldata _calldata) external; }
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.22;
import { BosonTypes } from "../../domain/BosonTypes.sol";
/**
* @title IBosonExchangeEvents
*
* @notice Defines events related to exchanges within the protocol.
*/
interface IBosonExchangeEvents {
event BuyerCommitted(
uint256 indexed offerId,
uint256 indexed buyerId,
uint256 indexed exchangeId,
BosonTypes.Exchange exchange,
BosonTypes.Voucher voucher,
address executedBy
);
event SellerCommitted(
uint256 indexed offerId,
uint256 indexed sellerId,
uint256 indexed exchangeId,
BosonTypes.Exchange exchange,
BosonTypes.Voucher voucher,
address executedBy
);
event BuyerInitiatedOfferSetSellerParams(
uint256 indexed offerId,
uint256 indexed sellerId,
BosonTypes.SellerOfferParams sellerParams,
address executedBy
);
event ExchangeCompleted(
uint256 indexed offerId,
uint256 indexed buyerId,
uint256 indexed exchangeId,
address executedBy
);
event VoucherCanceled(uint256 indexed offerId, uint256 indexed exchangeId, address indexed executedBy);
event VoucherExpired(uint256 indexed offerId, uint256 indexed exchangeId, address indexed executedBy);
event VoucherExtended(
uint256 indexed offerId,
uint256 indexed exchangeId,
uint256 validUntil,
address indexed executedBy
);
event VoucherRedeemed(uint256 indexed offerId, uint256 indexed exchangeId, address indexed executedBy);
event VoucherRevoked(uint256 indexed offerId, uint256 indexed exchangeId, address indexed executedBy);
event VoucherTransferred(
uint256 indexed offerId,
uint256 indexed exchangeId,
uint256 indexed newBuyerId,
address executedBy
);
event ConditionalCommitAuthorized(
uint256 indexed offerId,
BosonTypes.GatingType gating,
address indexed buyerAddress,
uint256 indexed tokenId,
uint256 commitCount,
uint256 maxCommits
);
}// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.22;
/**
* @title IBosonFundsBaseEvents
*
* @notice Defines events related to management of funds within the protocol.
*/
interface IBosonFundsBaseEvents {
event FundsDeposited(
uint256 indexed entityId,
address indexed executedBy,
address indexed tokenAddress,
uint256 amount
);
event FundsEncumbered(
uint256 indexed entityId,
address indexed exchangeToken,
uint256 amount,
address indexed executedBy
);
event FundsReleased(
uint256 indexed exchangeId,
uint256 indexed entityId,
address indexed exchangeToken,
uint256 amount,
address executedBy
);
event ProtocolFeeCollected(
uint256 indexed exchangeId,
address indexed exchangeToken,
uint256 amount,
address indexed executedBy
);
event FundsWithdrawn(
uint256 indexed sellerId,
address indexed withdrawnTo,
address indexed tokenAddress,
uint256 amount,
address executedBy
);
event DRFeeRequested(
uint256 indexed exchangeId,
address indexed tokenAddress,
uint256 feeAmount,
address indexed mutualizerAddress,
address executedBy
);
event DRFeeReturned(
uint256 indexed exchangeId,
address indexed tokenAddress,
uint256 returnAmount,
address indexed mutualizerAddress,
address executedBy
);
event DRFeeReturnFailed(
uint256 indexed exchangeId,
address indexed tokenAddress,
uint256 returnAmount,
address indexed mutualizerAddress,
address executedBy
);
}// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.22;
import { BosonTypes } from "../../domain/BosonTypes.sol";
import { BosonErrors } from "../../domain/BosonErrors.sol";
import { IBosonExchangeEvents } from "../events/IBosonExchangeEvents.sol";
import { IBosonFundsBaseEvents } from "../events/IBosonFundsEvents.sol";
/**
* @title ISequentialCommitHandler
*
* @notice Handles sequential commits.
*
* The ERC-165 identifier for this interface is: 0x34780cc6
*/
interface IBosonSequentialCommitHandler is BosonErrors, IBosonExchangeEvents, IBosonFundsBaseEvents {
/**
* @notice Commits to an existing exchange. Price discovery is offloaded to external contract.
*
* Emits a BuyerCommitted event if successful.
* Transfers voucher to the buyer address.
*
* Reverts if:
* - The exchanges region of protocol is paused
* - The buyers region of protocol is paused
* - Buyer address is zero
* - Exchange does not exist
* - Exchange is not in Committed state
* - Voucher has expired
* - It is a bid order and:
* - Caller is not the voucher holder
* - Voucher owner did not approve protocol to transfer the voucher
* - Price received from price discovery is lower than the expected price
* - It is a ask order and:
* - Offer price is in native token and caller does not send enough
* - Offer price is in some ERC20 token and caller also sends native currency
* - Calling transferFrom on token fails for some reason (e.g. protocol is not approved to transfer)
* - Received ERC20 token amount differs from the expected value
* - Protocol does not receive the voucher
* - Transfer of voucher to the buyer fails for some reason (e.g. buyer is contract that doesn't accept voucher)
* - Reseller did not approve protocol to transfer exchange token in escrow
* - Call to price discovery contract fails
* - Protocol fee and royalties combined exceed the secondary price
* - The secondary price cannot cover the buyer's cancellation penalty
* - Transfer of exchange token fails
*
* @param _buyer - the buyer's address (caller can commit on behalf of a buyer)
* @param _exchangeId - the id of the exchange to commit to
* @param _priceDiscovery - the fully populated BosonTypes.PriceDiscovery struct
*/
function sequentialCommitToOffer(
address payable _buyer,
uint256 _exchangeId,
BosonTypes.PriceDiscovery calldata _priceDiscovery
) external payable;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity 0.8.22;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity 0.8.22;
/**
* @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 v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity 0.8.22;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
/**
* @title IWrappedNative
*
* @notice Provides the minimum interface for native token wrapper
*/
interface IWrappedNative {
function withdraw(uint256) external;
function deposit() external payable;
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
function approve(address, uint256) external returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
import "../../domain/BosonConstants.sol";
import { BosonErrors } from "../../domain/BosonErrors.sol";
import { BosonTypes } from "../../domain/BosonTypes.sol";
import { ProtocolLib } from "../libs/ProtocolLib.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IBosonFundsBaseEvents } from "../../interfaces/events/IBosonFundsEvents.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { IDRFeeMutualizer } from "../../interfaces/clients/IDRFeeMutualizer.sol";
import { Context } from "@openzeppelin/contracts/utils/Context.sol";
import { IWrappedNative } from "../../interfaces/IWrappedNative.sol";
/**
* @title FundsBase
*
* @dev
*/
abstract contract FundsBase is Context {
using SafeERC20 for IERC20;
IWrappedNative internal immutable wNative;
/**
* @notice Takes in the offer id and entity id and encumbers the appropriate funds during commitToOffer.
* For seller-created offers: encumbers seller's pre-deposited deposit and validates buyer's incoming payment.
* For buyer-created offers: encumbers buyer's pre-deposited payment and validates seller's incoming deposit.
* If offer is preminted, caller's funds are not encumbered, but the funds are covered from pre-deposited amounts.
*
* Emits FundsEncumbered event if successful.
*
* Reverts if:
* - Incoming payment is in native token and caller does not send enough
* - Incoming payment is in some ERC20 token and caller also sends native currency
* - Contract at token address does not support ERC20 function transferFrom
* - Calling transferFrom on token fails for some reason (e.g. protocol is not approved to transfer)
* - Entity has less pre-deposited funds available than required amount
* - Received ERC20 token amount differs from the expected value
*
* @param _offerId - id of the offer with the details
* @param _entityId - id of the committing entity (buyer for seller-created offers, seller for buyer-created offers)
* @param _incomingAmount - the amount being paid by the committing entity
* @param _isPreminted - flag indicating if the offer is preminted
* @param _priceType - price type, either static or discovery
*/
function encumberFunds(
uint256 _offerId,
uint256 _entityId,
uint256 _incomingAmount,
bool _isPreminted,
BosonTypes.PriceType _priceType
) internal {
// Load protocol entities storage
ProtocolLib.ProtocolEntities storage pe = ProtocolLib.protocolEntities();
// get message sender
address sender = _msgSender();
// fetch offer to get the exchange token, price and seller
// this will be called only from commitToOffer so we expect that exchange actually exist
BosonTypes.Offer storage offer = pe.offers[_offerId];
address exchangeToken = offer.exchangeToken;
if (!_isPreminted) {
validateIncomingPayment(exchangeToken, _incomingAmount);
emit IBosonFundsBaseEvents.FundsDeposited(_entityId, sender, exchangeToken, _incomingAmount);
emit IBosonFundsBaseEvents.FundsEncumbered(_entityId, exchangeToken, _incomingAmount, sender);
}
if (offer.creator == BosonTypes.OfferCreator.Buyer) {
decreaseAvailableFunds(offer.buyerId, exchangeToken, offer.price);
emit IBosonFundsBaseEvents.FundsEncumbered(offer.buyerId, exchangeToken, offer.price, sender);
} else {
uint256 sellerId = offer.sellerId;
bool isPriceDiscovery = _priceType == BosonTypes.PriceType.Discovery;
uint256 sellerFundsEncumbered = offer.sellerDeposit +
(_isPreminted && !isPriceDiscovery ? _incomingAmount : 0);
decreaseAvailableFunds(sellerId, exchangeToken, sellerFundsEncumbered);
emit IBosonFundsBaseEvents.FundsEncumbered(sellerId, exchangeToken, sellerFundsEncumbered, sender);
}
}
/**
* @notice Validates that incoming payments matches expectation. If token is a native currency, it makes sure
* msg.value is correct. If token is ERC20, it transfers the value from the sender to the protocol.
*
* Emits ERC20 Transfer event in call stack if successful.
*
* Reverts if:
* - Offer price is in native token and caller does not send enough
* - Offer price is in some ERC20 token and caller also sends native currency
* - Contract at token address does not support ERC20 function transferFrom
* - Calling transferFrom on token fails for some reason (e.g. protocol is not approved to transfer)
* - Received ERC20 token amount differs from the expected value
*
* @param _exchangeToken - address of the token (0x for native currency)
* @param _value - value expected to receive
*/
function validateIncomingPayment(address _exchangeToken, uint256 _value) internal {
if (_exchangeToken == address(0)) {
// if transfer is in the native currency, msg.value must match offer price
if (msg.value != _value) revert BosonErrors.InsufficientValueReceived();
} else {
// when price is in an erc20 token, transferring the native currency is not allowed
if (msg.value != 0) revert BosonErrors.NativeNotAllowed();
// if transfer is in ERC20 token, try to transfer the amount from buyer to the protocol
transferFundsIn(_exchangeToken, _value);
}
}
/**
* @notice Takes in the exchange id and releases the funds to buyer, seller and dispute resolver depending on the state of the exchange.
* It is called only from finalizeExchange and finalizeDispute.
*
* Emits FundsReleased and/or ProtocolFeeCollected event if payoffs are warranted and transaction is successful.
*
* @param _exchangeId - exchange id
*/
function releaseFunds(uint256 _exchangeId) internal {
// Load protocol entities storage
ProtocolLib.ProtocolEntities storage pe = ProtocolLib.protocolEntities();
// Get the exchange and its state
// Since this should be called only from certain functions from exchangeHandler and disputeHandler
// exchange must exist and be in a completed state, so that's not checked explicitly
BosonTypes.Exchange storage exchange = pe.exchanges[_exchangeId];
// Get offer from storage to get the details about sellerDeposit, price, sellerId, exchangeToken and buyerCancelPenalty
BosonTypes.Offer storage offer = pe.offers[exchange.offerId];
// calculate the payoffs depending on state exchange is in
BosonTypes.Payoff memory payoff;
BosonTypes.OfferFees storage offerFee = pe.offerFees[exchange.offerId];
uint256 offerPrice = offer.priceType == BosonTypes.PriceType.Discovery ? 0 : offer.price;
BosonTypes.ExchangeCosts[] storage exchangeCosts = pe.exchangeCosts[_exchangeId];
uint256 lastPrice = exchangeCosts.length == 0 ? offerPrice : exchangeCosts[exchangeCosts.length - 1].price;
{
// scope to avoid stack too deep errors
BosonTypes.ExchangeState exchangeState = exchange.state;
uint256 sellerDeposit = offer.sellerDeposit;
bool isEscalated = pe.disputeDates[_exchangeId].escalated != 0;
if (exchangeState == BosonTypes.ExchangeState.Completed) {
// COMPLETED
payoff.protocol = offerFee.protocolFee;
// buyerPayoff is 0
payoff.agent = offerFee.agentFee;
payoff.seller = offerPrice + sellerDeposit - payoff.protocol - payoff.agent;
} else if (exchangeState == BosonTypes.ExchangeState.Revoked) {
// REVOKED
// sellerPayoff is 0
payoff.buyer = lastPrice + sellerDeposit;
} else if (exchangeState == BosonTypes.ExchangeState.Canceled) {
// CANCELED
uint256 buyerCancelPenalty = offer.buyerCancelPenalty;
payoff.seller = sellerDeposit + buyerCancelPenalty;
payoff.buyer = lastPrice - buyerCancelPenalty;
} else if (exchangeState == BosonTypes.ExchangeState.Disputed) {
// DISPUTED
// determine if buyerEscalationDeposit was encumbered or not
// if dispute was escalated, disputeDates.escalated is populated
uint256 buyerEscalationDeposit = isEscalated
? pe.disputeResolutionTerms[exchange.offerId].buyerEscalationDeposit
: 0;
// get the information about the dispute, which must exist
BosonTypes.Dispute storage dispute = pe.disputes[_exchangeId];
BosonTypes.DisputeState disputeState = dispute.state;
if (disputeState == BosonTypes.DisputeState.Retracted) {
// RETRACTED - same as "COMPLETED"
payoff.protocol = offerFee.protocolFee;
payoff.agent = offerFee.agentFee;
// buyerPayoff is 0
payoff.seller =
offerPrice +
sellerDeposit -
payoff.protocol -
payoff.agent +
buyerEscalationDeposit;
// DR is paid if dispute was escalated
payoff.disputeResolver = isEscalated ? pe.disputeResolutionTerms[exchange.offerId].feeAmount : 0;
} else if (disputeState == BosonTypes.DisputeState.Refused) {
// REFUSED
payoff.seller = sellerDeposit;
payoff.buyer = lastPrice + buyerEscalationDeposit;
// DR is not paid when dispute is refused
} else {
// RESOLVED or DECIDED
uint256 commonPot = sellerDeposit + buyerEscalationDeposit;
payoff.buyer = applyPercent(commonPot, dispute.buyerPercent);
payoff.seller = commonPot - payoff.buyer;
payoff.buyer = payoff.buyer + applyPercent(lastPrice, dispute.buyerPercent);
payoff.seller = payoff.seller + offerPrice - applyPercent(offerPrice, dispute.buyerPercent);
// DR is always paid for escalated disputes (Decided or Resolved with escalation)
if (isEscalated) {
payoff.disputeResolver = pe.disputeResolutionTerms[exchange.offerId].feeAmount;
}
}
}
}
address exchangeToken = offer.exchangeToken;
// Original seller and last buyer are done
// Release funds to intermediate sellers (if they exist)
// and add the protocol fee to the total
{
(uint256 sequentialProtocolFee, uint256 sequentialRoyalties) = releaseFundsToIntermediateSellers(
_exchangeId,
exchange.state,
offerPrice,
exchangeToken,
offer
);
payoff.seller += sequentialRoyalties;
payoff.protocol += sequentialProtocolFee;
}
// Store payoffs to availablefunds and notify the external observers
address sender = _msgSender();
if (payoff.seller > 0) {
increaseAvailableFundsAndEmitEvent(_exchangeId, offer.sellerId, exchangeToken, payoff.seller, sender);
}
if (payoff.buyer > 0) {
increaseAvailableFundsAndEmitEvent(_exchangeId, exchange.buyerId, exchangeToken, payoff.buyer, sender);
}
if (payoff.protocol > 0) {
increaseAvailableFunds(PROTOCOL_ENTITY_ID, exchangeToken, payoff.protocol);
emit IBosonFundsBaseEvents.ProtocolFeeCollected(_exchangeId, exchangeToken, payoff.protocol, sender);
}
if (payoff.agent > 0) {
// Get the agent for offer
uint256 agentId = ProtocolLib.protocolLookups().agentIdByOffer[exchange.offerId];
increaseAvailableFundsAndEmitEvent(_exchangeId, agentId, exchangeToken, payoff.agent, sender);
}
BosonTypes.DisputeResolutionTerms memory drTerms = pe.disputeResolutionTerms[offer.id];
if (payoff.disputeResolver > 0) {
increaseAvailableFundsAndEmitEvent(
_exchangeId,
drTerms.disputeResolverId,
exchangeToken,
payoff.disputeResolver,
sender
);
}
// Return unused DR fee to mutualizer or seller's pool
if (drTerms.feeAmount != 0) {
payoff.mutualizer = drTerms.feeAmount - payoff.disputeResolver;
// Use exchange-level mutualizer address (locked at commitment time)
address mutualizerAddress = exchange.mutualizerAddress;
if (mutualizerAddress == address(0)) {
if (payoff.mutualizer > 0) {
increaseAvailableFundsAndEmitEvent(
_exchangeId,
offer.sellerId,
exchangeToken,
payoff.mutualizer,
sender
);
}
} else {
if (payoff.mutualizer > 0) {
if (exchangeToken == address(0)) {
exchangeToken = address(wNative);
wNative.deposit{ value: payoff.mutualizer }();
}
uint256 oldAllowance = IERC20(exchangeToken).allowance(address(this), mutualizerAddress);
IERC20(exchangeToken).forceApprove(mutualizerAddress, payoff.mutualizer + oldAllowance);
}
try
IDRFeeMutualizer(mutualizerAddress).finalizeExchange{
gas: ProtocolLib.protocolLimits().mutualizerGasStipend
}(_exchangeId, payoff.mutualizer)
{
emit IBosonFundsBaseEvents.DRFeeReturned(
_exchangeId,
exchangeToken,
payoff.mutualizer,
mutualizerAddress,
sender
);
} catch {
// Ignore failure to not block the main flow
emit IBosonFundsBaseEvents.DRFeeReturnFailed(
_exchangeId,
exchangeToken,
payoff.mutualizer,
mutualizerAddress,
sender
);
}
}
}
}
/**
* @notice Takes the exchange id and releases the funds to original seller if offer.priceType is Discovery
* and to all intermediate resellers in case of sequential commit, depending on the state of the exchange.
* It is called only from releaseFunds. Protocol fee and royalties are calculated and returned to releaseFunds, where they are added to the total.
*
* Emits FundsReleased events for non zero payoffs.
*
* @param _exchangeId - exchange id
* @param _exchangeState - state of the exchange
* @param _initialPrice - initial price of the offer
* @param _exchangeToken - address of the token used for the exchange
* @param _offer - offer struct
* @return protocolFee - protocol fee from secondary sales
* @return sellerRoyalties - royalties from secondary sales collected for the seller
*/
function releaseFundsToIntermediateSellers(
uint256 _exchangeId,
BosonTypes.ExchangeState _exchangeState,
uint256 _initialPrice,
address _exchangeToken,
BosonTypes.Offer storage _offer
) internal returns (uint256 protocolFee, uint256 sellerRoyalties) {
BosonTypes.ExchangeCosts[] storage exchangeCosts;
// calculate effective price multiplier
uint256 effectivePriceMultiplier;
{
ProtocolLib.ProtocolEntities storage pe = ProtocolLib.protocolEntities();
exchangeCosts = pe.exchangeCosts[_exchangeId];
// if price type was static and no sequential commit happened, just return
if (exchangeCosts.length == 0) {
return (0, 0);
}
{
if (_exchangeState == BosonTypes.ExchangeState.Completed) {
// COMPLETED, buyer pays full price
effectivePriceMultiplier = HUNDRED_PERCENT;
} else if (
_exchangeState == BosonTypes.ExchangeState.Revoked ||
_exchangeState == BosonTypes.ExchangeState.Canceled
) {
// REVOKED or CANCELED, buyer pays nothing (buyerCancelPenalty is not considered payment)
effectivePriceMultiplier = 0;
} else if (_exchangeState == BosonTypes.ExchangeState.Disputed) {
// DISPUTED
// get the information about the dispute, which must exist
BosonTypes.Dispute storage dispute = pe.disputes[_exchangeId];
BosonTypes.DisputeState disputeState = dispute.state;
if (disputeState == BosonTypes.DisputeState.Retracted) {
// RETRACTED - same as "COMPLETED"
effectivePriceMultiplier = HUNDRED_PERCENT;
} else if (disputeState == BosonTypes.DisputeState.Refused) {
// REFUSED, buyer pays nothing
effectivePriceMultiplier = 0;
} else {
// RESOLVED or DECIDED
effectivePriceMultiplier = HUNDRED_PERCENT - dispute.buyerPercent;
}
}
}
}
uint256 resellerBuyPrice = _initialPrice; // the price that reseller paid for the voucher
address msgSender = _msgSender();
uint256 len = exchangeCosts.length;
for (uint256 i = 0; i < len; ) {
// Since all elements of exchangeCosts[i] are used, it makes sense to copy them to memory
BosonTypes.ExchangeCosts memory secondaryCommit = exchangeCosts[i];
// amount to be released
uint256 currentResellerAmount;
// inside the scope to avoid stack too deep error
{
if (effectivePriceMultiplier > 0) {
protocolFee =
protocolFee +
applyPercent(secondaryCommit.protocolFeeAmount, effectivePriceMultiplier);
sellerRoyalties += distributeRoyalties(
_exchangeId,
_offer,
secondaryCommit,
effectivePriceMultiplier
);
}
// secondary price without protocol fee and royalties
uint256 reducedSecondaryPrice = secondaryCommit.price -
secondaryCommit.protocolFeeAmount -
secondaryCommit.royaltyAmount;
// Calculate amount to be released to the reseller:
// + part of the price that they paid (relevant for unhappy paths)
// + price of the voucher that they sold reduced for part that goes to next reseller, royalties and protocol fee
// - immediate payout that was released already during the sequential commit
currentResellerAmount =
applyPercent(resellerBuyPrice, (HUNDRED_PERCENT - effectivePriceMultiplier)) +
secondaryCommit.price -
applyPercent(secondaryCommit.price, (HUNDRED_PERCENT - effectivePriceMultiplier)) -
applyPercent(secondaryCommit.protocolFeeAmount, effectivePriceMultiplier) -
applyPercent(secondaryCommit.royaltyAmount, effectivePriceMultiplier) -
Math.min(resellerBuyPrice, reducedSecondaryPrice);
resellerBuyPrice = secondaryCommit.price;
}
if (currentResellerAmount > 0) {
increaseAvailableFundsAndEmitEvent(
_exchangeId,
secondaryCommit.resellerId,
_exchangeToken,
currentResellerAmount,
msgSender
);
}
unchecked {
i++;
}
}
}
/**
* @notice Forwards values to increaseAvailableFunds and emits notifies external listeners.
*
* Emits FundsReleased events
*
* @param _exchangeId - exchange id
* @param _entityId - id of the entity to which the funds are released
* @param _tokenAddress - address of the token used for the exchange
* @param _amount - amount of tokens to be released
* @param _sender - address of the sender that executed the transaction
*/
function increaseAvailableFundsAndEmitEvent(
uint256 _exchangeId,
uint256 _entityId,
address _tokenAddress,
uint256 _amount,
address _sender
) internal {
increaseAvailableFunds(_entityId, _tokenAddress, _amount);
emit IBosonFundsBaseEvents.FundsReleased(_exchangeId, _entityId, _tokenAddress, _amount, _sender);
}
/**
* @notice Tries to transfer tokens from the caller to the protocol.
*
* Emits ERC20 Transfer event in call stack if successful.
*
* Reverts if:
* - Contract at token address does not support ERC20 function transferFrom
* - Calling transferFrom on token fails for some reason (e.g. protocol is not approved to transfer)
* - Received ERC20 token amount differs from the expected value
*
* @param _tokenAddress - address of the token to be transferred
* @param _from - address to transfer funds from
* @param _amount - amount to be transferred
*/
function transferFundsIn(address _tokenAddress, address _from, uint256 _amount) internal {
if (_amount > 0) {
// protocol balance before the transfer
uint256 protocolTokenBalanceBefore = IERC20(_tokenAddress).balanceOf(address(this));
// transfer ERC20 tokens from the caller
IERC20(_tokenAddress).safeTransferFrom(_from, address(this), _amount);
// protocol balance after the transfer
uint256 protocolTokenBalanceAfter = IERC20(_tokenAddress).balanceOf(address(this));
// make sure that expected amount of tokens was transferred
if (protocolTokenBalanceAfter - protocolTokenBalanceBefore != _amount)
revert BosonErrors.InsufficientValueReceived();
}
}
/**
* @notice Same as transferFundsIn(address _tokenAddress, address _from, uint256 _amount),
* but _from is message sender
*
* @param _tokenAddress - address of the token to be transferred
* @param _amount - amount to be transferred
*/
function transferFundsIn(address _tokenAddress, uint256 _amount) internal {
transferFundsIn(_tokenAddress, _msgSender(), _amount);
}
/**
* @notice Tries to transfer native currency or tokens from the protocol to the recipient.
*
* Emits FundsWithdrawn event if successful.
* Emits ERC20 Transfer event in call stack if ERC20 token is withdrawn and transfer is successful.
*
* Reverts if:
* - Transfer of native currency is not successful (i.e. recipient is a contract which reverted)
* - Contract at token address does not support ERC20 function transfer
* - Available funds is less than amount to be decreased
*
* @param _entityId - id of entity for which funds should be decreased, or 0 for protocol
* @param _tokenAddress - address of the token to be transferred
* @param _to - address of the recipient
* @param _amount - amount to be transferred
*/
function transferFundsOut(uint256 _entityId, address _tokenAddress, address payable _to, uint256 _amount) internal {
// first decrease the amount to prevent the reentrancy attack
decreaseAvailableFunds(_entityId, _tokenAddress, _amount);
// try to transfer the funds
transferFundsOut(_tokenAddress, _to, _amount);
// notify the external observers
emit IBosonFundsBaseEvents.FundsWithdrawn(_entityId, _to, _tokenAddress, _amount, _msgSender());
}
/**
* @notice Tries to transfer native currency or tokens from the protocol to the recipient.
*
* Emits ERC20 Transfer event in call stack if ERC20 token is withdrawn and transfer is successful.
*
* Reverts if:
* - Transfer of native currency is not successful (i.e. recipient is a contract which reverted)
* - Contract at token address does not support ERC20 function transfer
* - Available funds is less than amount to be decreased
*
* @param _tokenAddress - address of the token to be transferred
* @param _to - address of the recipient
* @param _amount - amount to be transferred
*/
function transferFundsOut(address _tokenAddress, address payable _to, uint256 _amount) internal {
// try to transfer the funds
if (_tokenAddress == address(0)) {
// transfer native currency
(bool success, ) = _to.call{ value: _amount }("");
if (!success) revert BosonErrors.TokenTransferFailed();
} else {
// transfer ERC20 tokens
IERC20(_tokenAddress).safeTransfer(_to, _amount);
}
}
/**
* @notice Increases the amount, available to withdraw or use as a seller deposit.
*
* @param _entityId - id of entity for which funds should be increased, or 0 for protocol
* @param _tokenAddress - funds contract address or zero address for native currency
* @param _amount - amount to be credited
*/
function increaseAvailableFunds(uint256 _entityId, address _tokenAddress, uint256 _amount) internal {
ProtocolLib.ProtocolLookups storage pl = ProtocolLib.protocolLookups();
// if the current amount of token is 0, the token address must be added to the token list
mapping(address => uint256) storage availableFunds = pl.availableFunds[_entityId];
if (availableFunds[_tokenAddress] == 0) {
address[] storage tokenList = pl.tokenList[_entityId];
tokenList.push(_tokenAddress);
//Set index mapping. Should be index in tokenList array + 1
pl.tokenIndexByAccount[_entityId][_tokenAddress] = tokenList.length;
}
// update the available funds
availableFunds[_tokenAddress] += _amount;
}
/**
* @notice Decreases the amount available to withdraw or use as a seller deposit.
*
* Reverts if:
* - Available funds is less than amount to be decreased
*
* @param _entityId - id of entity for which funds should be decreased, or 0 for protocol
* @param _tokenAddress - funds contract address or zero address for native currency
* @param _amount - amount to be taken away
*/
function decreaseAvailableFunds(uint256 _entityId, address _tokenAddress, uint256 _amount) internal {
if (_amount > 0) {
ProtocolLib.ProtocolLookups storage pl = ProtocolLib.protocolLookups();
// get available funds from storage
mapping(address => uint256) storage availableFunds = pl.availableFunds[_entityId];
uint256 entityFunds = availableFunds[_tokenAddress];
// make sure that seller has enough funds in the pool and reduce the available funds
if (entityFunds < _amount) revert BosonErrors.InsufficientAvailableFunds();
// Use unchecked to optimize execution cost. The math is safe because of the require above.
unchecked {
availableFunds[_tokenAddress] = entityFunds - _amount;
}
// if available funds are totally emptied, the token address is removed from the seller's tokenList
if (entityFunds == _amount) {
// Get the index in the tokenList array, which is 1 less than the tokenIndexByAccount index
address[] storage tokenList = pl.tokenList[_entityId];
uint256 lastTokenIndex = tokenList.length - 1;
mapping(address => uint256) storage entityTokens = pl.tokenIndexByAccount[_entityId];
uint256 index = entityTokens[_tokenAddress] - 1;
// if target is last index then only pop and delete are needed
// otherwise, we overwrite the target with the last token first
if (index != lastTokenIndex) {
// Need to fill gap caused by delete if more than one element in storage array
address tokenToMove = tokenList[lastTokenIndex];
// Copy the last token in the array to this index to fill the gap
tokenList[index] = tokenToMove;
// Reset index mapping. Should be index in tokenList array + 1
entityTokens[tokenToMove] = index + 1;
}
// Delete last token address in the array, which was just moved to fill the gap
tokenList.pop();
// Delete from index mapping
delete entityTokens[_tokenAddress];
}
}
}
/**
* @notice Distributes the royalties to external recipients and seller's treasury.
*
* @param _offer - storage pointer to the offer
* @param _secondaryCommit - information about the secondary commit (royaltyInfoIndex, price, escrowedRoyaltyAmount)
* @param _effectivePriceMultiplier - multiplier for the price, depending on the state of the exchange
*/
function distributeRoyalties(
uint256 _exchangeId,
BosonTypes.Offer storage _offer,
BosonTypes.ExchangeCosts memory _secondaryCommit,
uint256 _effectivePriceMultiplier
) internal returns (uint256 sellerRoyalties) {
address sender = _msgSender();
address exchangeToken = _offer.exchangeToken;
BosonTypes.RoyaltyInfo storage _royaltyInfo = _offer.royaltyInfo[_secondaryCommit.royaltyInfoIndex];
uint256 len = _royaltyInfo.recipients.length;
uint256 totalAmount;
uint256 effectivePrice = applyPercent(_secondaryCommit.price, _effectivePriceMultiplier);
ProtocolLib.ProtocolLookups storage pl = ProtocolLib.protocolLookups();
for (uint256 i = 0; i < len; ) {
address payable recipient = _royaltyInfo.recipients[i];
uint256 amount = applyPercent(_royaltyInfo.bps[i], effectivePrice);
totalAmount += amount;
if (recipient == address(0)) {
// goes to seller's treasury
sellerRoyalties += amount;
} else {
// Make funds available to withdraw
if (amount > 0) {
increaseAvailableFundsAndEmitEvent(
_exchangeId,
pl.royaltyRecipientIdByWallet[recipient],
exchangeToken,
amount,
sender
);
}
}
unchecked {
i++;
}
}
// if there is a remainder due to rounding, it goes to the seller's treasury
sellerRoyalties =
sellerRoyalties +
applyPercent(_secondaryCommit.royaltyAmount, _effectivePriceMultiplier) -
totalAmount;
}
/**
* @notice Returns the balance of the protocol for the given token address
*
* @param _tokenAddress - the address of the token to check the balance for
* @return balance - the balance of the protocol for the given token address
*/
function getBalance(address _tokenAddress) internal view returns (uint256) {
return _tokenAddress == address(0) ? address(this).balance : IERC20(_tokenAddress).balanceOf(address(this));
}
/**
* @notice Calulates the percentage of the amount.
*
* @param _amount - amount to be used for the calculation
* @param _percent - percentage to be calculated, in basis points (1% = 100, 100% = 10000)
*/
function applyPercent(uint256 _amount, uint256 _percent) internal pure returns (uint256) {
if (_percent == HUNDRED_PERCENT) return _amount;
if (_percent == 0) return 0;
return (_amount * _percent) / HUNDRED_PERCENT;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
import "./../../domain/BosonConstants.sol";
import { BosonErrors } from "../../domain/BosonErrors.sol";
import { ProtocolLib } from "../libs/ProtocolLib.sol";
import { BosonTypes } from "../../domain/BosonTypes.sol";
/**
* @title PausableBase
*
* @notice Provides modifiers for regional pausing
*/
contract PausableBase is BosonTypes {
/**
* @notice Modifier that checks the Offers region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier offersNotPaused() {
revertIfPaused(PausableRegion.Offers);
_;
}
/**
* @notice Modifier that checks the Twins region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier twinsNotPaused() {
revertIfPaused(PausableRegion.Twins);
_;
}
/**
* @notice Modifier that checks the Bundles region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier bundlesNotPaused() {
revertIfPaused(PausableRegion.Bundles);
_;
}
/**
* @notice Modifier that checks the Groups region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier groupsNotPaused() {
revertIfPaused(PausableRegion.Groups);
_;
}
/**
* @notice Modifier that checks the Sellers region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier sellersNotPaused() {
revertIfPaused(PausableRegion.Sellers);
_;
}
/**
* @notice Modifier that checks the Buyers region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier buyersNotPaused() {
revertIfPaused(PausableRegion.Buyers);
_;
}
/**
* @notice Modifier that checks the Agents region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier agentsNotPaused() {
revertIfPaused(PausableRegion.Agents);
_;
}
/**
* @notice Modifier that checks the DisputeResolvers region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier disputeResolversNotPaused() {
revertIfPaused(PausableRegion.DisputeResolvers);
_;
}
/**
* @notice Modifier that checks the Exchanges region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier exchangesNotPaused() {
revertIfPaused(PausableRegion.Exchanges);
_;
}
/**
* @notice Modifier that checks the Disputes region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier disputesNotPaused() {
revertIfPaused(PausableRegion.Disputes);
_;
}
/**
* @notice Modifier that checks the Funds region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier fundsNotPaused() {
revertIfPaused(PausableRegion.Funds);
_;
}
/**
* @notice Modifier that checks the Orchestration region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier orchestrationNotPaused() {
revertIfPaused(PausableRegion.Orchestration);
_;
}
/**
* @notice Modifier that checks the MetaTransaction region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier metaTransactionsNotPaused() {
revertIfPaused(PausableRegion.MetaTransaction);
_;
}
/**
* @notice Modifier that checks the PriceDiscovery region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier priceDiscoveryNotPaused() {
revertIfPaused(PausableRegion.PriceDiscovery);
_;
}
/**
* @notice Modifier that checks the SequentialCommit region is not paused
*
* Reverts if region is paused
*
* See: {BosonTypes.PausableRegion}
*/
modifier sequentialCommitNotPaused() {
revertIfPaused(PausableRegion.SequentialCommit);
_;
}
/**
* @notice Checks if a region of the protocol is paused.
*
* Reverts if region is paused
*
* @param _region the region to check pause status for
*/
function revertIfPaused(PausableRegion _region) internal view {
// Region enum value must be used as the exponent in a power of 2
uint256 powerOfTwo = 1 << uint256(_region);
if ((ProtocolLib.protocolStatus().pauseScenario & powerOfTwo) == powerOfTwo)
revert BosonErrors.RegionPaused(_region);
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
import "../../domain/BosonConstants.sol";
import { ProtocolLib } from "../libs/ProtocolLib.sol";
import { IWrappedNative } from "../../interfaces/IWrappedNative.sol";
import { IBosonVoucher } from "../../interfaces/clients/IBosonVoucher.sol";
import { IBosonPriceDiscovery } from "../../interfaces/clients/IBosonPriceDiscovery.sol";
import { ProtocolBase } from "./../bases/ProtocolBase.sol";
/**
* @title PriceDiscoveryBase
*
* @dev Provides methods for fulfiling orders on external price discovery contracts.
*/
contract PriceDiscoveryBase is ProtocolBase {
/**
* @notice
* For offers with native exchange token, it is expected that the price discovery contracts will
* operate with wrapped native token. Set the address of the wrapped native token in the constructor.
*
* @param _wNative - the address of the wrapped native token
*/
//solhint-disable-next-line
constructor(address _wNative) {
if (_wNative == address(0)) revert InvalidAddress();
wNative = IWrappedNative(_wNative);
}
/**
* @notice Fulfils an order on an external contract.
*
* If the owner is price discovery contract, the protocol cannot act as an intermediary in the exchange,
* and sellers must use Wrapped's contract. Wrappers handle ask and bid orders in the same manner.
*
* See descriptions of `fulfilAskOrder`, `fulfilBidOrder` and handleWrapper for more details.
*
* @param _tokenId - the id of the token. Accepts whatever token is sent by price discovery contract when this value is zero.
* @param _offer - the fully populated BosonTypes.Offer struct
* @param _priceDiscovery - the fully populated BosonTypes.PriceDiscovery struct
* @param _seller - the seller's address
* @param _buyer - the buyer's address (caller can commit on behalf of a buyer)
* @return actualPrice - the actual price of the order
*/
function fulfilOrder(
uint256 _tokenId,
Offer storage _offer,
PriceDiscovery calldata _priceDiscovery,
address _seller,
address _buyer
) internal priceDiscoveryNotPaused returns (uint256 actualPrice) {
// Make sure caller provided price discovery data
if (_priceDiscovery.priceDiscoveryContract == address(0) || _priceDiscovery.priceDiscoveryData.length == 0) {
revert InvalidPriceDiscovery();
}
// If not dealing with wrapper, voucher is transferred using the conduit which must not be zero address
if (_priceDiscovery.side != Side.Wrapper && _priceDiscovery.conduit == address(0))
revert InvalidConduitAddress();
IBosonVoucher bosonVoucher = IBosonVoucher(
getCloneAddress(protocolLookups(), _offer.sellerId, _offer.collectionIndex)
);
// Set incoming voucher clone address
protocolStatus().incomingVoucherCloneAddress = address(bosonVoucher);
if (_priceDiscovery.side == Side.Ask) {
actualPrice = fulfilAskOrder(
_tokenId,
_offer.id,
_offer.exchangeToken,
_priceDiscovery,
_seller,
_buyer,
bosonVoucher
);
} else if (_priceDiscovery.side == Side.Bid) {
actualPrice = fulfilBidOrder(_tokenId, _offer.exchangeToken, _priceDiscovery, _seller, bosonVoucher);
} else {
// _priceDiscovery.side == Side.Wrapper
// Handle wrapper voucher, there is no difference between ask and bid
actualPrice = handleWrapper(_tokenId, _offer.exchangeToken, _priceDiscovery, bosonVoucher);
}
// Price must be high enough to cover cancellation penalty in case of buyer's cancellation
if (actualPrice < _offer.buyerCancelPenalty) {
revert PriceDoesNotCoverPenalty();
}
}
/**
* @notice Fulfils an ask order on external contract.
*
* Reverts if:
* - Offer price is in native token and caller does not send enough
* - Offer price is in some ERC20 token and caller also sends native currency
* - Calling transferFrom on token fails for some reason (e.g. protocol is not approved to transfer)
* - Call to price discovery contract fails
* - Transfer of voucher to the buyer fails for some reason (e.g. buyer is contract that doesn't accept voucher)
* - Token id sent to buyer and token id set by the caller don't match (if caller has provided the token id)
* - Token id sent to buyer and it does not belong to the offer, set by the caller (if caller has not provided the token id)
*
* @param _tokenId - the id of the token (can be 0 if unknown)
* @param _offerId - the id of the offer
* @param _exchangeToken - the address of the exchange contract
* @param _priceDiscovery - the fully populated BosonTypes.PriceDiscovery struct
* @param _seller - the seller's address
* @param _buyer - the buyer's address (caller can commit on behalf of a buyer)
* @param _bosonVoucher - the boson voucher contract
* @return actualPrice - the actual price of the order
*/
function fulfilAskOrder(
uint256 _tokenId,
uint256 _offerId,
address _exchangeToken,
PriceDiscovery calldata _priceDiscovery,
address _seller,
address _buyer,
IBosonVoucher _bosonVoucher
) internal returns (uint256 actualPrice) {
// Cache price discovery contract address
address bosonPriceDiscovery = protocolAddresses().priceDiscovery;
// Transfer buyers funds to protocol and forward them to price discovery contract
if (_exchangeToken == address(0)) _exchangeToken = address(wNative);
validateIncomingPayment(_exchangeToken, _priceDiscovery.price);
transferFundsOut(_exchangeToken, payable(bosonPriceDiscovery), _priceDiscovery.price);
actualPrice = IBosonPriceDiscovery(bosonPriceDiscovery).fulfilAskOrder(
_exchangeToken,
_priceDiscovery,
_bosonVoucher,
payable(_msgSender())
);
_tokenId = getAndVerifyTokenId(_tokenId);
// Make sure that the exchange is part of the correct offer
if (_tokenId >> 128 != _offerId) revert TokenIdMismatch();
// Make sure that the price discovery contract has transferred the voucher to the protocol
if (_bosonVoucher.ownerOf(_tokenId) != bosonPriceDiscovery) revert VoucherNotReceived();
// Transfer voucher to buyer
_bosonVoucher.safeTransferFrom(bosonPriceDiscovery, _buyer, _tokenId);
// Price discovery should send funds to the seller.
// The seller must approve the protocol to transfer the funds before the order is fulfilled.
transferFundsIn(_exchangeToken, _seller, actualPrice);
}
/**
* @notice Fulfils a bid order on external contract.
*
* Reverts if:
* - Token id not set by the caller
* - Call to price discovery contract fails
* - Token id sent to buyer and token id set by the caller don't match
*
* @param _exchangeToken - the address of the exchange token
* @param _priceDiscovery - the fully populated BosonTypes.PriceDiscovery struct
* @param _seller - the seller's address
* @param _bosonVoucher - the boson voucher contract
* @return actualPrice - the actual price of the order
*/
function fulfilBidOrder(
uint256 _tokenId,
address _exchangeToken,
PriceDiscovery calldata _priceDiscovery,
address _seller,
IBosonVoucher _bosonVoucher
) internal returns (uint256 actualPrice) {
if (_tokenId == 0) revert TokenIdMandatory();
address sender = _msgSender();
if (_seller != sender) revert NotVoucherHolder();
// Cache price discovery contract address
address bosonPriceDiscovery = protocolAddresses().priceDiscovery;
// Transfer seller's voucher to protocol
// Don't need to use safe transfer from, since that protocol can handle the voucher
_bosonVoucher.transferFrom(_seller, bosonPriceDiscovery, _tokenId);
actualPrice = IBosonPriceDiscovery(bosonPriceDiscovery).fulfilBidOrder{ value: msg.value }(
_tokenId,
_exchangeToken,
_priceDiscovery,
_seller,
_bosonVoucher
);
// Verify that token id provided by caller matches the token id that the price discovery contract has sent to buyer
getAndVerifyTokenId(_tokenId);
}
/**
* @notice Call `unwrap` (or equivalent) function on the price discovery contract.
*
* Reverts if:
* - Token id not set by the caller
* - The wrapper does not own the voucher
* - Token id sent to buyer and token id set by the caller don't match
*
* @param _tokenId - the id of the token
* @param _exchangeToken - the address of the exchange contract
* @param _priceDiscovery - the fully populated BosonTypes.PriceDiscovery struct
* @param _bosonVoucher - the boson voucher contract
* @return actualPrice - the actual price of the order
*/
function handleWrapper(
uint256 _tokenId,
address _exchangeToken,
PriceDiscovery calldata _priceDiscovery,
IBosonVoucher _bosonVoucher
) internal returns (uint256 actualPrice) {
if (_tokenId == 0) revert TokenIdMandatory();
// If price discovery contract does not own the voucher, it cannot be classified as a wrapper
address owner = _bosonVoucher.ownerOf(_tokenId);
if (owner != _priceDiscovery.priceDiscoveryContract) revert NotVoucherHolder();
// Cache price discovery contract address
address bosonPriceDiscovery = protocolAddresses().priceDiscovery;
actualPrice = IBosonPriceDiscovery(bosonPriceDiscovery).handleWrapper{ value: msg.value }(
_exchangeToken,
_priceDiscovery
);
// Verify that token id provided by caller matches the token id that the price discovery contract has sent to buyer
getAndVerifyTokenId(_tokenId);
}
/*
* @notice Returns the token id that the price discovery contract has sent to the protocol or buyer
*
* Reverts if:
* - Caller has provided token id, but it does not match the token id that the price discovery contract has sent to the protocol
*
* @param _tokenId - the token id that the caller has provided
* @return tokenId - the token id that the price discovery contract has sent to the protocol
*/
function getAndVerifyTokenId(uint256 _tokenId) internal view returns (uint256) {
// Store the information about incoming voucher
ProtocolLib.ProtocolStatus storage ps = protocolStatus();
// If caller has provided token id, it must match the token id that the price discovery send to the protocol
if (_tokenId != 0) {
if (_tokenId != ps.incomingVoucherId) revert TokenIdMismatch();
} else {
// If caller has not provided token id, use the one stored in onPremintedVoucherTransfer function
_tokenId = ps.incomingVoucherId;
}
// Token id cannot be zero at this point
if (_tokenId == 0) revert TokenIdNotSet();
return _tokenId;
}
/*
* @notice Resets value of incoming voucher id and incoming voucher clone address to 0
* This is called at the end of the methods that interacts with price discovery contracts
*
*/
function clearPriceDiscoveryStorage() internal {
ProtocolLib.ProtocolStatus storage ps = protocolStatus();
delete ps.incomingVoucherId;
delete ps.incomingVoucherCloneAddress;
}
}// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.22;
import "../../domain/BosonConstants.sol";
import { BosonErrors } from "../../domain/BosonErrors.sol";
import { ProtocolLib } from "../libs/ProtocolLib.sol";
import { DiamondLib } from "../../diamond/DiamondLib.sol";
import { BosonTypes } from "../../domain/BosonTypes.sol";
import { PausableBase } from "./PausableBase.sol";
import { FundsBase } from "./FundsBase.sol";
import { ReentrancyGuardBase } from "./ReentrancyGuardBase.sol";
/**
* @title ProtocolBase
*
* @notice Provides domain and common modifiers to Protocol facets
*/
abstract contract ProtocolBase is PausableBase, FundsBase, ReentrancyGuardBase, BosonErrors {
/**
* @notice Modifier to protect initializer function from being invoked twice.
*/
modifier onlyUninitialized(bytes4 interfaceId) {
ProtocolLib.ProtocolStatus storage ps = protocolStatus();
if (ps.initializedInterfaces[interfaceId]) revert AlreadyInitialized();
ps.initializedInterfaces[interfaceId] = true;
_;
}
/**
* @notice Modifier that checks that the caller has a specific role.
*
* Reverts if caller doesn't have role.
*
* See: {AccessController.hasRole}
*
* @param _role - the role to check
*/
modifier onlyRole(bytes32 _role) {
DiamondLib.DiamondStorage storage ds = DiamondLib.diamondStorage();
if (!ds.accessController.hasRole(_role, _msgSender())) revert AccessDenied();
_;
}
/**
* @notice Get the Protocol Addresses slot
*
* @return pa - the Protocol Addresses slot
*/
function protocolAddresses() internal pure returns (ProtocolLib.ProtocolAddresses storage pa) {
pa = ProtocolLib.protocolAddresses();
}
/**
* @notice Get the Protocol Limits slot
*
* @return pl - the Protocol Limits slot
*/
function protocolLimits() internal pure returns (ProtocolLib.ProtocolLimits storage pl) {
pl = ProtocolLib.protocolLimits();
}
/**
* @notice Get the Protocol Entities slot
*
* @return pe - the Protocol Entities slot
*/
function protocolEntities() internal pure returns (ProtocolLib.ProtocolEntities storage pe) {
pe = ProtocolLib.protocolEntities();
}
/**
* @notice Get the Protocol Lookups slot
*
* @return pl - the Protocol Lookups slot
*/
function protocolLookups() internal pure returns (ProtocolLib.ProtocolLookups storage pl) {
pl = ProtocolLib.protocolLookups();
}
/**
* @notice Get the Protocol Fees slot
*
* @return pf - the Protocol Fees slot
*/
function protocolFees() internal pure returns (ProtocolLib.ProtocolFees storage pf) {
pf = ProtocolLib.protocolFees();
}
/**
* @notice Get the Protocol Counters slot
*
* @return pc the Protocol Counters slot
*/
function protocolCounters() internal pure returns (ProtocolLib.ProtocolCounters storage pc) {
pc = ProtocolLib.protocolCounters();
}
/**
* @notice Get the Protocol meta-transactions storage slot
*
* @return pmti the Protocol meta-transactions storage slot
*/
function protocolMetaTxInfo() internal pure returns (ProtocolLib.ProtocolMetaTxInfo storage pmti) {
pmti = ProtocolLib.protocolMetaTxInfo();
}
/**
* @notice Get the Protocol Status slot
*
* @return ps the Protocol Status slot
*/
function protocolStatus() internal pure returns (ProtocolLib.ProtocolStatus storage ps) {
ps = ProtocolLib.protocolStatus();
}
/**
* @notice Gets a seller id from storage by assistant address
*
* @param _assistant - the assistant address of the seller
* @return exists - whether the seller id exists
* @return sellerId - the seller id
*/
function getSellerIdByAssistant(address _assistant) internal view returns (bool exists, uint256 sellerId) {
// Get the seller id
sellerId = protocolLookups().sellerIdByAssistant[_assistant];
// Determine existence
exists = (sellerId > 0);
}
/**
* @notice Gets a seller id from storage by admin address
*
* @param _admin - the admin address of the seller
* @return exists - whether the seller id exists
* @return sellerId - the seller id
*/
function getSellerIdByAdmin(address _admin) internal view returns (bool exists, uint256 sellerId) {
// Get the seller id
sellerId = protocolLookups().sellerIdByAdmin[_admin];
// Determine existence
exists = (sellerId > 0);
}
/**
* @notice Gets a seller id from storage by auth token. A seller will have either an admin address or an auth token
*
* @param _authToken - the potential _authToken of the seller.
* @return exists - whether the seller id exists
* @return sellerId - the seller id
*/
function getSellerIdByAuthToken(
AuthToken calldata _authToken
) internal view returns (bool exists, uint256 sellerId) {
// Get the seller id
sellerId = protocolLookups().sellerIdByAuthToken[_authToken.tokenType][_authToken.tokenId];
// Determine existence
exists = (sellerId > 0);
}
/**
* @notice Gets a buyer id from storage by wallet address
*
* @param _wallet - the wallet address of the buyer
* @return exists - whether the buyer id exists
* @return buyerId - the buyer id
*/
function getBuyerIdByWallet(address _wallet) internal view returns (bool exists, uint256 buyerId) {
// Get the buyer id
buyerId = protocolLookups().buyerIdByWallet[_wallet];
// Determine existence
exists = (buyerId > 0);
}
/**
* @notice Gets a agent id from storage by wallet address
*
* @param _wallet - the wallet address of the buyer
* @return exists - whether the buyer id exists
* @return agentId - the buyer id
*/
function getAgentIdByWallet(address _wallet) internal view returns (bool exists, uint256 agentId) {
// Get the buyer id
agentId = protocolLookups().agentIdByWallet[_wallet];
// Determine existence
exists = (agentId > 0);
}
/**
* @notice Gets a dispute resolver id from storage by assistant address
*
* @param _assistant - the assistant address of the dispute resolver
* @return exists - whether the dispute resolver id exists
* @return disputeResolverId - the dispute resolver id
*/
function getDisputeResolverIdByAssistant(
address _assistant
) internal view returns (bool exists, uint256 disputeResolverId) {
// Get the dispute resolver id
disputeResolverId = protocolLookups().disputeResolverIdByAssistant[_assistant];
// Determine existence
exists = (disputeResolverId > 0);
}
/**
* @notice Gets a dispute resolver id from storage by admin address
*
* @param _admin - the admin address of the dispute resolver
* @return exists - whether the dispute resolver id exists
* @return disputeResolverId - the dispute resolver id
*/
function getDisputeResolverIdByAdmin(
address _admin
) internal view returns (bool exists, uint256 disputeResolverId) {
// Get the dispute resolver id
disputeResolverId = protocolLookups().disputeResolverIdByAdmin[_admin];
// Determine existence
exists = (disputeResolverId > 0);
}
/**
* @notice Gets a group id from storage by offer id
*
* @param _offerId - the offer id
* @return exists - whether the group id exists
* @return groupId - the group id.
*/
function getGroupIdByOffer(uint256 _offerId) internal view returns (bool exists, uint256 groupId) {
// Get the group id
groupId = protocolLookups().groupIdByOffer[_offerId];
// Determine existence
exists = (groupId > 0);
}
/**
* @notice Fetches a given seller from storage by id
*
* @param _sellerId - the id of the seller
* @return exists - whether the seller exists
* @return seller - the seller details. See {BosonTypes.Seller}
* @return authToken - optional AuthToken struct that specifies an AuthToken type and tokenId that the user can use to do admin functions
*/
function fetchSeller(
uint256 _sellerId
) internal view returns (bool exists, Seller storage seller, AuthToken storage authToken) {
// Cache protocol entities for reference
ProtocolLib.ProtocolEntities storage entities = protocolEntities();
// Get the seller's slot
seller = entities.sellers[_sellerId];
//Get the seller's auth token's slot
authToken = entities.authTokens[_sellerId];
// Determine existence
exists = (_sellerId > 0 && seller.id == _sellerId);
}
/**
* @notice Fetches a given buyer from storage by id
*
* @param _buyerId - the id of the buyer
* @return exists - whether the buyer exists
* @return buyer - the buyer details. See {BosonTypes.Buyer}
*/
function fetchBuyer(uint256 _buyerId) internal view returns (bool exists, BosonTypes.Buyer storage buyer) {
// Get the buyer's slot
buyer = protocolEntities().buyers[_buyerId];
// Determine existence
exists = (_buyerId > 0 && buyer.id == _buyerId);
}
/**
* @notice Fetches a given dispute resolver from storage by id
*
* @param _disputeResolverId - the id of the dispute resolver
* @return exists - whether the dispute resolver exists
* @return disputeResolver - the dispute resolver details. See {BosonTypes.DisputeResolver}
* @return disputeResolverFees - list of fees dispute resolver charges per token type. Zero address is native currency. See {BosonTypes.DisputeResolverFee}
*/
function fetchDisputeResolver(
uint256 _disputeResolverId
)
internal
view
returns (
bool exists,
BosonTypes.DisputeResolver storage disputeResolver,
BosonTypes.DisputeResolverFee[] storage disputeResolverFees
)
{
// Cache protocol entities for reference
ProtocolLib.ProtocolEntities storage entities = protocolEntities();
// Get the dispute resolver's slot
disputeResolver = entities.disputeResolvers[_disputeResolverId];
//Get dispute resolver's fee list slot
disputeResolverFees = entities.disputeResolverFees[_disputeResolverId];
// Determine existence
exists = (_disputeResolverId > 0 && disputeResolver.id == _disputeResolverId);
}
/**
* @notice Fetches a given agent from storage by id
*
* @param _agentId - the id of the agent
* @return exists - whether the agent exists
* @return agent - the agent details. See {BosonTypes.Agent}
*/
function fetchAgent(uint256 _agentId) internal view returns (bool exists, BosonTypes.Agent storage agent) {
// Get the agent's slot
agent = protocolEntities().agents[_agentId];
// Determine existence
exists = (_agentId > 0 && agent.id == _agentId);
}
/**
* @notice Fetches a given offer from storage by id
*
* @param _offerId - the id of the offer
* @return exists - whether the offer exists
* @return offer - the offer details. See {BosonTypes.Offer}
*/
function fetchOffer(uint256 _offerId) internal view returns (bool exists, Offer storage offer) {
// Get the offer's slot
offer = protocolEntities().offers[_offerId];
// Determine existence
exists = (_offerId > 0 && offer.id == _offerId);
}
/**
* @notice Fetches the offer dates from storage by offer id
*
* @param _offerId - the id of the offer
* @return offerDates - the offer dates details. See {BosonTypes.OfferDates}
*/
function fetchOfferDates(uint256 _offerId) internal view returns (BosonTypes.OfferDates storage offerDates) {
// Get the offerDates slot
offerDates = protocolEntities().offerDates[_offerId];
}
/**
* @notice Fetches the offer durations from storage by offer id
*
* @param _offerId - the id of the offer
* @return offerDurations - the offer durations details. See {BosonTypes.OfferDurations}
*/
function fetchOfferDurations(
uint256 _offerId
) internal view returns (BosonTypes.OfferDurations storage offerDurations) {
// Get the offer's slot
offerDurations = protocolEntities().offerDurations[_offerId];
}
/**
* @notice Fetches the dispute resolution terms from storage by offer id
*
* @param _offerId - the id of the offer
* @return disputeResolutionTerms - the details about the dispute resolution terms. See {BosonTypes.DisputeResolutionTerms}
*/
function fetchDisputeResolutionTerms(
uint256 _offerId
) internal view returns (BosonTypes.DisputeResolutionTerms storage disputeResolutionTerms) {
// Get the disputeResolutionTerms slot
disputeResolutionTerms = protocolEntities().disputeResolutionTerms[_offerId];
}
/**
* @notice Fetches a given group from storage by id
*
* @param _groupId - the id of the group
* @return exists - whether the group exists
* @return group - the group details. See {BosonTypes.Group}
*/
function fetchGroup(uint256 _groupId) internal view returns (bool exists, Group storage group) {
// Get the group's slot
group = protocolEntities().groups[_groupId];
// Determine existence
exists = (_groupId > 0 && group.id == _groupId);
}
/**
* @notice Fetches the Condition from storage by group id
*
* @param _groupId - the id of the group
* @return condition - the condition details. See {BosonTypes.Condition}
*/
function fetchCondition(uint256 _groupId) internal view returns (BosonTypes.Condition storage condition) {
// Get the offerDates slot
condition = protocolEntities().conditions[_groupId];
}
/**
* @notice Fetches a given exchange from storage by id
*
* @param _exchangeId - the id of the exchange
* @return exists - whether the exchange exists
* @return exchange - the exchange details. See {BosonTypes.Exchange}
*/
function fetchExchange(uint256 _exchangeId) internal view returns (bool exists, Exchange storage exchange) {
// Get the exchange's slot
exchange = protocolEntities().exchanges[_exchangeId];
// Determine existence
exists = (_exchangeId > 0 && exchange.id == _exchangeId);
}
/**
* @notice Fetches a given voucher from storage by exchange id
*
* @param _exchangeId - the id of the exchange associated with the voucher
* @return voucher - the voucher details. See {BosonTypes.Voucher}
*/
function fetchVoucher(uint256 _exchangeId) internal view returns (Voucher storage voucher) {
// Get the voucher
voucher = protocolEntities().vouchers[_exchangeId];
}
/**
* @notice Fetches a given dispute from storage by exchange id
*
* @param _exchangeId - the id of the exchange associated with the dispute
* @return exists - whether the dispute exists
* @return dispute - the dispute details. See {BosonTypes.Dispute}
*/
function fetchDispute(
uint256 _exchangeId
) internal view returns (bool exists, Dispute storage dispute, DisputeDates storage disputeDates) {
// Cache protocol entities for reference
ProtocolLib.ProtocolEntities storage entities = protocolEntities();
// Get the dispute's slot
dispute = entities.disputes[_exchangeId];
// Get the disputeDates slot
disputeDates = entities.disputeDates[_exchangeId];
// Determine existence
exists = (_exchangeId > 0 && dispute.exchangeId == _exchangeId);
}
/**
* @notice Fetches a given twin from storage by id
*
* @param _twinId - the id of the twin
* @return exists - whether the twin exists
* @return twin - the twin details. See {BosonTypes.Twin}
*/
function fetchTwin(uint256 _twinId) internal view returns (bool exists, Twin storage twin) {
// Get the twin's slot
twin = protocolEntities().twins[_twinId];
// Determine existence
exists = (_twinId > 0 && twin.id == _twinId);
}
/**
* @notice Fetches a given bundle from storage by id
*
* @param _bundleId - the id of the bundle
* @return exists - whether the bundle exists
* @return bundle - the bundle details. See {BosonTypes.Bundle}
*/
function fetchBundle(uint256 _bundleId) internal view returns (bool exists, Bundle storage bundle) {
// Get the bundle's slot
bundle = protocolEntities().bundles[_bundleId];
// Determine existence
exists = (_bundleId > 0 && bundle.id == _bundleId);
}
/**
* @notice Gets offer from protocol storage, makes sure it exist and not voided
*
* Reverts if:
* - Offer does not exist
* - Offer already voided
*
* @param _offerId - the id of the offer to check
*/
function getValidOffer(uint256 _offerId) internal view returns (Offer storage offer) {
bool exists;
// Get offer
(exists, offer) = fetchOffer(_offerId);
// Offer must already exist
if (!exists) revert NoSuchOffer();
// Offer must not already be voided
if (offer.voided) revert OfferHasBeenVoided();
}
/**
* @notice Gets offer and seller from protocol storage
*
* Reverts if:
* - Offer does not exist
* - Offer already voided
* - Seller assistant is not the caller
*
* @param _offerId - the id of the offer to check
* @return offer - the offer details. See {BosonTypes.Offer}
*/
function getValidOfferWithSellerCheck(uint256 _offerId) internal view returns (Offer storage offer) {
// Get offer
offer = getValidOffer(_offerId);
// Get seller, we assume seller exists if offer exists
(, Seller storage seller, ) = fetchSeller(offer.sellerId);
// Caller must be seller's assistant address
if (seller.assistant != _msgSender()) revert NotAssistant();
}
/**
* @notice Gets a valid offer from storage and checks that the caller is authorized to modify it
*
* Reverts if:
* - Offer id is invalid
* - Offer has already been voided
* - Caller is not authorized (for seller-created offers: not the seller assistant; for buyer-created offers: not the buyer who created it)
*
* @param _offerId - the id of the offer to check
* @return offer - the offer details. See {BosonTypes.Offer}
* @return creatorId - the id of the creator (sellerId for seller-created offers, buyerId for buyer-created offers)
*/
function getValidOfferWithCreatorCheck(
uint256 _offerId
) internal view returns (Offer storage offer, uint256 creatorId) {
// Get offer
offer = getValidOffer(_offerId);
if (offer.creator == OfferCreator.Seller) {
// For seller-created offers, check that caller is the seller's assistant
(, Seller storage seller, ) = fetchSeller(offer.sellerId);
if (seller.assistant != _msgSender()) revert NotAssistant();
creatorId = offer.sellerId;
} else if (offer.creator == OfferCreator.Buyer) {
// For buyer-created offers, check that caller is the buyer who created the offer
(, Buyer storage buyer) = fetchBuyer(offer.buyerId);
if (buyer.wallet != _msgSender()) revert NotOfferCreator();
creatorId = offer.buyerId;
}
}
/**
* @notice Gets the bundle id for a given offer id.
*
* @param _offerId - the offer id.
* @return exists - whether the bundle id exists
* @return bundleId - the bundle id.
*/
function fetchBundleIdByOffer(uint256 _offerId) internal view returns (bool exists, uint256 bundleId) {
// Get the bundle id
bundleId = protocolLookups().bundleIdByOffer[_offerId];
// Determine existence
exists = (bundleId > 0);
}
/**
* @notice Gets the bundle id for a given twin id.
*
* @param _twinId - the twin id.
* @return exists - whether the bundle id exist
* @return bundleId - the bundle id.
*/
function fetchBundleIdByTwin(uint256 _twinId) internal view returns (bool exists, uint256 bundleId) {
// Get the bundle id
bundleId = protocolLookups().bundleIdByTwin[_twinId];
// Determine existence
exists = (bundleId > 0);
}
/**
* @notice Gets the exchange ids for a given offer id.
*
* @param _offerId - the offer id.
* @return exists - whether the exchange Ids exist
* @return exchangeIds - the exchange Ids.
*/
function getExchangeIdsByOffer(
uint256 _offerId
) internal view returns (bool exists, uint256[] storage exchangeIds) {
// Get the exchange Ids
exchangeIds = protocolLookups().exchangeIdsByOffer[_offerId];
// Determine existence
exists = (exchangeIds.length > 0);
}
/**
* @notice Make sure the caller is buyer associated with the exchange
*
* Reverts if
* - caller is not the buyer associated with exchange
*
* @param _currentBuyer - id of current buyer associated with the exchange
*/
function checkBuyer(uint256 _currentBuyer) internal view {
// Get the caller's buyer account id
(, uint256 buyerId) = getBuyerIdByWallet(_msgSender());
// Must be the buyer associated with the exchange (which is always voucher holder)
if (buyerId != _currentBuyer) revert NotVoucherHolder();
}
/**
* @notice Get a valid exchange and its associated voucher
*
* Reverts if
* - Exchange does not exist
* - Exchange is not in the expected state
*
* @param _exchangeId - the id of the exchange to complete
* @param _expectedState - the state the exchange should be in
* @return exchange - the exchange
* @return voucher - the voucher
*/
function getValidExchange(
uint256 _exchangeId,
ExchangeState _expectedState
) internal view returns (Exchange storage exchange, Voucher storage voucher) {
// Get the exchange
bool exchangeExists;
(exchangeExists, exchange) = fetchExchange(_exchangeId);
// Make sure the exchange exists
if (!exchangeExists) revert NoSuchExchange();
// Make sure the exchange is in expected state
if (exchange.state != _expectedState) revert InvalidState();
// Get the voucher
voucher = fetchVoucher(_exchangeId);
}
uint256 private constant ADDRESS_LENGTH = 20;
/**
* @notice Returns the current sender address.
*/
function _msgSender() internal view override returns (address) {
uint256 msgDataLength = msg.data.length;
if (msg.sender == address(this) && msgDataLength >= ADDRESS_LENGTH) {
unchecked {
return address(bytes20(msg.data[msgDataLength - ADDRESS_LENGTH:]));
}
} else {
return msg.sender;
}
}
/**
* @notice Gets the agent id for a given offer id.
*
* @param _offerId - the offer id.
* @return exists - whether the exchange id exist
* @return agentId - the agent id.
*/
function fetchAgentIdByOffer(uint256 _offerId) internal view returns (bool exists, uint256 agentId) {
// Get the agent id
agentId = protocolLookups().agentIdByOffer[_offerId];
// Determine existence
exists = (agentId > 0);
}
/**
* @notice Fetches the offer fees from storage by offer id
*
* @param _offerId - the id of the offer
* @return offerFees - the offer fees details. See {BosonTypes.OfferFees}
*/
function fetchOfferFees(uint256 _offerId) internal view returns (BosonTypes.OfferFees storage offerFees) {
// Get the offerFees slot
offerFees = protocolEntities().offerFees[_offerId];
}
/**
* @notice Fetches a list of twin receipts from storage by exchange id
*
* @param _exchangeId - the id of the exchange
* @return exists - whether one or more twin receipt exists
* @return twinReceipts - the list of twin receipts. See {BosonTypes.TwinReceipt}
*/
function fetchTwinReceipts(
uint256 _exchangeId
) internal view returns (bool exists, TwinReceipt[] storage twinReceipts) {
// Get the twin receipts slot
twinReceipts = protocolLookups().twinReceiptsByExchange[_exchangeId];
// Determine existence
exists = (_exchangeId > 0 && twinReceipts.length > 0);
}
/**
* @notice Fetches a condition from storage by exchange id
*
* @param _exchangeId - the id of the exchange
* @return exists - whether one condition exists for the exchange
* @return condition - the condition. See {BosonTypes.Condition}
*/
function fetchConditionByExchange(
uint256 _exchangeId
) internal view returns (bool exists, Condition storage condition) {
// Get the condition slot
condition = protocolLookups().exchangeCondition[_exchangeId];
// Determine existence
exists = (_exchangeId > 0 && condition.method != EvaluationMethod.None);
}
/**
* @notice calculate the protocol fee amount for a given exchange
*
* @param _exchangeToken - the token used for the exchange
* @param _price - the price of the exchange
* @return protocolFee - the protocol fee
*/
function _getProtocolFee(address _exchangeToken, uint256 _price) internal view returns (uint256 protocolFee) {
// Check if the exchange token is the Boson token
if (_exchangeToken == protocolAddresses().token) {
// Return the flatBoson fee percentage if the exchange token is the Boson token
return protocolFees().flatBoson;
}
uint256 feePercentage = _getFeePercentage(_exchangeToken, _price);
return applyPercent(_price, feePercentage);
}
/**
* @notice calculate the protocol fee percentage for a given exchange
*
* @param _exchangeToken - the token used for the exchange
* @param _price - the price of the exchange
* @return feePercentage - the protocol fee percentage based on token price (using protocol fee table)
*/
function _getFeePercentage(address _exchangeToken, uint256 _price) internal view returns (uint256 feePercentage) {
if (_exchangeToken == protocolAddresses().token) revert FeeTableAssetNotSupported();
ProtocolLib.ProtocolFees storage fees = protocolFees();
uint256[] storage priceRanges = fees.tokenPriceRanges[_exchangeToken];
uint256[] storage feePercentages = fees.tokenFeePercentages[_exchangeToken];
// If the token has a custom fee table, find the appropriate percentage
uint256 priceRangesLength = priceRanges.length;
if (priceRangesLength > 0) {
unchecked {
uint256 i;
for (; i < priceRangesLength - 1; ++i) {
if (_price <= priceRanges[i]) {
// Return the fee percentage for the matching price range
return feePercentages[i];
}
}
// If price exceeds all ranges, use the highest fee percentage
return feePercentages[i];
}
}
// If no custom fee table exists, fallback to using the default protocol percentage
return fees.percentage;
}
/**
* @notice Fetches a clone address from storage by seller id and collection index
* If the collection index is 0, the clone address is the seller's main collection,
* otherwise it is the clone address of the additional collection at the given index.
*
* @param _lookups - storage slot for protocol lookups
* @param _sellerId - the id of the seller
* @param _collectionIndex - the index of the collection
* @return cloneAddress - the clone address
*/
function getCloneAddress(
ProtocolLib.ProtocolLookups storage _lookups,
uint256 _sellerId,
uint256 _collectionIndex
) internal view returns (address cloneAddress) {
return
_collectionIndex == 0
? _lookups.cloneAddress[_sellerId]
: _lookups.additionalCollections[_sellerId][_collectionIndex - 1].collectionAddress;
}
/**
* @notice Internal helper to get royalty information and seller for a chosen exchange.
*
* Reverts if exchange does not exist.
*
* @param _queryId - offer id or exchange id
* @param _isExchangeId - indicates if the query represents the exchange id
* @return royaltyInfo - list of royalty recipients and corresponding bps
* @return royaltyInfoIndex - index of the royalty info
* @return treasury - the seller's treasury address
*/
function fetchRoyalties(
uint256 _queryId,
bool _isExchangeId
) internal view returns (RoyaltyInfo storage royaltyInfo, uint256 royaltyInfoIndex, address treasury) {
RoyaltyInfo[] storage royaltyInfoAll;
if (_isExchangeId) {
(bool exists, Exchange storage exchange) = fetchExchange(_queryId);
if (!exists) revert NoSuchExchange();
_queryId = exchange.offerId;
}
// not using fetchOffer to reduce gas costs (limitation of royalty registry)
ProtocolLib.ProtocolEntities storage pe = protocolEntities();
Offer storage offer = pe.offers[_queryId];
treasury = pe.sellers[offer.sellerId].treasury;
royaltyInfoAll = pe.offers[_queryId].royaltyInfo;
uint256 royaltyInfoLength = royaltyInfoAll.length;
if (royaltyInfoLength == 0) revert NoSuchOffer();
royaltyInfoIndex = royaltyInfoLength - 1;
// get the last royalty info
return (royaltyInfoAll[royaltyInfoIndex], royaltyInfoIndex, treasury);
}
/**
* @notice Helper function that calculates the total royalty percentage for a given exchange
*
* @param _bps - storage slot for array of royalty percentages
* @return totalBps - the total royalty percentage
*/
function getTotalRoyaltyPercentage(uint256[] storage _bps) internal view returns (uint256 totalBps) {
uint256 bpsLength = _bps.length;
for (uint256 i = 0; i < bpsLength; ) {
totalBps += _bps[i];
unchecked {
i++;
}
}
}
}// SPDX-License-Identifier: MIT
import "../../domain/BosonConstants.sol";
import { BosonErrors } from "../../domain/BosonErrors.sol";
import { ProtocolLib } from "../libs/ProtocolLib.sol";
pragma solidity 0.8.22;
/**
* @notice Contract module that helps prevent reentrant calls to a function.
*
* The majority of code, comments and general idea is taken from OpenZeppelin implementation.
* Code was adjusted to work with the storage layout used in the protocol.
* Reference implementation: OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
*
* 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.
*
* @dev 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 ReentrancyGuardBase {
/**
* @notice 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() {
ProtocolLib.ProtocolStatus storage ps = ProtocolLib.protocolStatus();
// On the first call to nonReentrant, ps.reentrancyStatus will be NOT_ENTERED
if (ps.reentrancyStatus == ENTERED) revert BosonErrors.ReentrancyGuard();
// Any calls to nonReentrant after this point will fail
ps.reentrancyStatus = ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
ps.reentrancyStatus = NOT_ENTERED;
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.22;
import { BosonTypes } from "../../domain/BosonTypes.sol";
/**
* @title ProtocolLib
*
* @notice Provides access to the protocol addresses, limits, entities, fees, counters, initializers and metaTransactions slots for Facets.
*/
library ProtocolLib {
bytes32 internal constant PROTOCOL_ADDRESSES_POSITION = keccak256("boson.protocol.addresses");
bytes32 internal constant PROTOCOL_LIMITS_POSITION = keccak256("boson.protocol.limits");
bytes32 internal constant PROTOCOL_ENTITIES_POSITION = keccak256("boson.protocol.entities");
bytes32 internal constant PROTOCOL_LOOKUPS_POSITION = keccak256("boson.protocol.lookups");
bytes32 internal constant PROTOCOL_FEES_POSITION = keccak256("boson.protocol.fees");
bytes32 internal constant PROTOCOL_COUNTERS_POSITION = keccak256("boson.protocol.counters");
bytes32 internal constant PROTOCOL_STATUS_POSITION = keccak256("boson.protocol.initializers");
bytes32 internal constant PROTOCOL_META_TX_POSITION = keccak256("boson.protocol.metaTransactions");
// Protocol addresses storage
struct ProtocolAddresses {
// Address of the Boson Protocol treasury
address payable treasury;
// Address of the Boson Token (ERC-20 contract)
address payable token;
// Address of the Boson Protocol Voucher beacon
address voucherBeacon;
// Address of the Boson Beacon proxy implementation
address beaconProxy;
// Address of the Boson Price Discovery
address priceDiscovery;
}
// Protocol limits storage
struct ProtocolLimits {
// limit on the resolution period that a seller can specify
uint256 maxResolutionPeriod;
// limit on the escalation response period that a dispute resolver can specify
uint256 maxEscalationResponsePeriod;
// lower limit for dispute period
uint256 minDisputePeriod;
// limit how many exchanges can be processed in single batch transaction
uint16 maxExchangesPerBatch;
// limit how many offers can be added to the group
uint16 maxOffersPerGroup;
// limit how many offers can be added to the bundle
uint16 maxOffersPerBundle;
// limit how many twins can be added to the bundle
uint16 maxTwinsPerBundle;
// limit how many offers can be processed in single batch transaction
uint16 maxOffersPerBatch;
// limit how many different tokens can be withdrawn in a single transaction
uint16 maxTokensPerWithdrawal;
// limit how many dispute resolver fee structs can be processed in a single transaction
uint16 maxFeesPerDisputeResolver;
// limit how many disputes can be processed in single batch transaction
uint16 maxDisputesPerBatch;
// limit how many sellers can be added to or removed from an allow list in a single transaction
uint16 maxAllowedSellers;
// limit the sum of (protocol fee percentage + agent fee percentage) of an offer fee
uint16 maxTotalOfferFeePercentage;
// limit the max royalty percentage that can be set by the seller
uint16 maxRoyaltyPercentage;
// limit the max number of vouchers that can be preminted in a single transaction
uint256 maxPremintedVouchers;
// lower limit for resolution period
uint256 minResolutionPeriod;
// Gas to forward when returning DR fee to mutualizer
uint256 mutualizerGasStipend;
}
// Protocol fees storage
struct ProtocolFees {
// Default percentage that will be taken as a fee from the net of a Boson Protocol exchange.
// This fee is returned if no fee ranges are configured in the fee table for the given asset.
uint256 percentage; // 1.75% = 175, 100% = 10000
// Flat fee taken for exchanges in $BOSON
uint256 flatBoson;
// buyer escalation deposit percentage
uint256 buyerEscalationDepositPercentage;
// Token-specific fee tables
mapping(address => uint256[]) tokenPriceRanges; // Price ranges for each token
mapping(address => uint256[]) tokenFeePercentages; // Fee percentages for each price range
}
// Protocol entities storage
struct ProtocolEntities {
// offer id => offer
mapping(uint256 => BosonTypes.Offer) offers;
// offer id => offer dates
mapping(uint256 => BosonTypes.OfferDates) offerDates;
// offer id => offer fees
mapping(uint256 => BosonTypes.OfferFees) offerFees;
// offer id => offer durations
mapping(uint256 => BosonTypes.OfferDurations) offerDurations;
// offer id => dispute resolution terms
mapping(uint256 => BosonTypes.DisputeResolutionTerms) disputeResolutionTerms;
// exchange id => exchange
mapping(uint256 => BosonTypes.Exchange) exchanges;
// exchange id => voucher
mapping(uint256 => BosonTypes.Voucher) vouchers;
// exchange id => dispute
mapping(uint256 => BosonTypes.Dispute) disputes;
// exchange id => dispute dates
mapping(uint256 => BosonTypes.DisputeDates) disputeDates;
// seller id => seller
mapping(uint256 => BosonTypes.Seller) sellers;
// buyer id => buyer
mapping(uint256 => BosonTypes.Buyer) buyers;
// dispute resolver id => dispute resolver
mapping(uint256 => BosonTypes.DisputeResolver) disputeResolvers;
// dispute resolver id => dispute resolver fee array
mapping(uint256 => BosonTypes.DisputeResolverFee[]) disputeResolverFees;
// agent id => agent
mapping(uint256 => BosonTypes.Agent) agents;
// group id => group
mapping(uint256 => BosonTypes.Group) groups;
// group id => condition
mapping(uint256 => BosonTypes.Condition) conditions;
// bundle id => bundle
mapping(uint256 => BosonTypes.Bundle) bundles;
// twin id => twin
mapping(uint256 => BosonTypes.Twin) twins;
// entity id => auth token
mapping(uint256 => BosonTypes.AuthToken) authTokens;
// exchange id => sequential commit info
mapping(uint256 => BosonTypes.ExchangeCosts[]) exchangeCosts;
// entity id => royalty recipient account
mapping(uint256 => BosonTypes.RoyaltyRecipient) royaltyRecipients;
}
// Protocol lookups storage
struct ProtocolLookups {
// offer id => exchange ids
mapping(uint256 => uint256[]) exchangeIdsByOffer;
// offer id => bundle id
mapping(uint256 => uint256) bundleIdByOffer;
// twin id => bundle id
mapping(uint256 => uint256) bundleIdByTwin;
// offer id => group id
mapping(uint256 => uint256) groupIdByOffer;
// offer id => agent id
mapping(uint256 => uint256) agentIdByOffer;
// seller assistant address => sellerId
mapping(address => uint256) sellerIdByAssistant;
// seller admin address => sellerId
mapping(address => uint256) sellerIdByAdmin;
// seller clerk address => sellerId
// @deprecated sellerIdByClerk is no longer used. Keeping it for backwards compatibility.
mapping(address => uint256) sellerIdByClerk;
// buyer wallet address => buyerId
mapping(address => uint256) buyerIdByWallet;
// dispute resolver assistant address => disputeResolverId
mapping(address => uint256) disputeResolverIdByAssistant;
// dispute resolver admin address => disputeResolverId
mapping(address => uint256) disputeResolverIdByAdmin;
// dispute resolver clerk address => disputeResolverId
// @deprecated disputeResolverIdByClerk is no longer used. Keeping it for backwards compatibility.
mapping(address => uint256) disputeResolverIdByClerk;
// dispute resolver id to fee token address => index of the token address
mapping(uint256 => mapping(address => uint256)) disputeResolverFeeTokenIndex;
// agent wallet address => agentId
mapping(address => uint256) agentIdByWallet;
// account id => token address => amount
mapping(uint256 => mapping(address => uint256)) availableFunds;
// account id => all tokens with balance > 0
mapping(uint256 => address[]) tokenList;
// account id => token address => index on token addresses list
mapping(uint256 => mapping(address => uint256)) tokenIndexByAccount;
// seller id => cloneAddress
mapping(uint256 => address) cloneAddress;
// buyer id => number of active vouchers
mapping(uint256 => uint256) voucherCount;
// buyer address => groupId => commit count (addresses that have committed to conditional offers)
mapping(address => mapping(uint256 => uint256)) conditionalCommitsByAddress;
// AuthTokenType => Auth NFT contract address.
mapping(BosonTypes.AuthTokenType => address) authTokenContracts;
// AuthTokenType => tokenId => sellerId
mapping(BosonTypes.AuthTokenType => mapping(uint256 => uint256)) sellerIdByAuthToken;
// seller id => token address (only ERC721) => start and end of token ids range
mapping(uint256 => mapping(address => BosonTypes.TokenRange[])) twinRangesBySeller;
// seller id => token address (only ERC721) => twin ids
// @deprecated twinIdsByTokenAddressAndBySeller is no longer used. Keeping it for backwards compatibility.
mapping(uint256 => mapping(address => uint256[])) twinIdsByTokenAddressAndBySeller;
// exchange id => BosonTypes.TwinReceipt
mapping(uint256 => BosonTypes.TwinReceipt[]) twinReceiptsByExchange;
// dispute resolver id => list of allowed sellers
mapping(uint256 => uint256[]) allowedSellers;
// dispute resolver id => seller id => index of allowed seller in allowedSellers
mapping(uint256 => mapping(uint256 => uint256)) allowedSellerIndex;
// exchange id => condition
mapping(uint256 => BosonTypes.Condition) exchangeCondition;
// groupId => offerId => index on Group.offerIds array
mapping(uint256 => mapping(uint256 => uint256)) offerIdIndexByGroup;
// seller id => Seller
mapping(uint256 => BosonTypes.Seller) pendingAddressUpdatesBySeller;
// seller id => AuthToken
mapping(uint256 => BosonTypes.AuthToken) pendingAuthTokenUpdatesBySeller;
// dispute resolver id => DisputeResolver
mapping(uint256 => BosonTypes.DisputeResolver) pendingAddressUpdatesByDisputeResolver;
// twin id => range id
mapping(uint256 => uint256) rangeIdByTwin;
// tokenId => groupId => commit count (count how many times a token has been used as gate for this group)
mapping(uint256 => mapping(uint256 => uint256)) conditionalCommitsByTokenId;
// seller id => collections
mapping(uint256 => BosonTypes.Collection[]) additionalCollections;
// seller id => seller salt used to create collections
mapping(uint256 => bytes32) sellerSalt;
// seller salt => is used
mapping(bytes32 => bool) isUsedSellerSalt;
// seller id => royalty recipients info
mapping(uint256 => BosonTypes.RoyaltyRecipientInfo[]) royaltyRecipientsBySeller;
// seller id => royalty recipient => index of royalty recipient in royaltyRecipientsBySeller
mapping(uint256 => mapping(address => uint256)) royaltyRecipientIndexBySellerAndRecipient;
// royalty recipient wallet address => agentId
mapping(address => uint256) royaltyRecipientIdByWallet;
// offer hash -> offer id
mapping(bytes32 => uint256) offerIdByHash;
}
// Incrementing id counters
struct ProtocolCounters {
// Next account id
uint256 nextAccountId;
// Next offer id
uint256 nextOfferId;
// Next exchange id
uint256 nextExchangeId;
// Next twin id
uint256 nextTwinId;
// Next group id
uint256 nextGroupId;
// Next twin id
uint256 nextBundleId;
}
// Storage related to Meta Transactions
struct ProtocolMetaTxInfo {
// [deprecated]
bytes32 deprecatedSlot;
// The domain Separator of the protocol
bytes32 domainSeparator;
// address => nonce => nonce used indicator
mapping(address => mapping(uint256 => bool)) usedNonce;
// The cached chain id
uint256 cachedChainId;
// map function name to input type
mapping(string => BosonTypes.MetaTxInputType) inputType;
// map input type => hash info
mapping(BosonTypes.MetaTxInputType => BosonTypes.HashInfo) hashInfo;
// Can function be executed using meta transactions
mapping(bytes32 => bool) isAllowlisted;
}
// Individual facet initialization states
struct ProtocolStatus {
// the current pause scenario, a sum of PausableRegions as powers of two
uint256 pauseScenario;
// reentrancy status
uint256 reentrancyStatus;
// interface id => initialized?
mapping(bytes4 => bool) initializedInterfaces;
// version => initialized?
mapping(bytes32 => bool) initializedVersions;
// Current protocol version
bytes32 version;
// Incoming voucher id
uint256 incomingVoucherId;
// Incoming voucher clone address
address incomingVoucherCloneAddress;
}
/**
* @dev Gets the protocol addresses slot
*
* @return pa - the protocol addresses slot
*/
function protocolAddresses() internal pure returns (ProtocolAddresses storage pa) {
bytes32 position = PROTOCOL_ADDRESSES_POSITION;
assembly {
pa.slot := position
}
}
/**
* @notice Gets the protocol limits slot
*
* @return pl - the protocol limits slot
*/
function protocolLimits() internal pure returns (ProtocolLimits storage pl) {
bytes32 position = PROTOCOL_LIMITS_POSITION;
assembly {
pl.slot := position
}
}
/**
* @notice Gets the protocol entities slot
*
* @return pe - the protocol entities slot
*/
function protocolEntities() internal pure returns (ProtocolEntities storage pe) {
bytes32 position = PROTOCOL_ENTITIES_POSITION;
assembly {
pe.slot := position
}
}
/**
* @notice Gets the protocol lookups slot
*
* @return pl - the protocol lookups slot
*/
function protocolLookups() internal pure returns (ProtocolLookups storage pl) {
bytes32 position = PROTOCOL_LOOKUPS_POSITION;
assembly {
pl.slot := position
}
}
/**
* @notice Gets the protocol fees slot
*
* @return pf - the protocol fees slot
*/
function protocolFees() internal pure returns (ProtocolFees storage pf) {
bytes32 position = PROTOCOL_FEES_POSITION;
assembly {
pf.slot := position
}
}
/**
* @notice Gets the protocol counters slot
*
* @return pc - the protocol counters slot
*/
function protocolCounters() internal pure returns (ProtocolCounters storage pc) {
bytes32 position = PROTOCOL_COUNTERS_POSITION;
assembly {
pc.slot := position
}
}
/**
* @notice Gets the protocol meta-transactions storage slot
*
* @return pmti - the protocol meta-transactions storage slot
*/
function protocolMetaTxInfo() internal pure returns (ProtocolMetaTxInfo storage pmti) {
bytes32 position = PROTOCOL_META_TX_POSITION;
assembly {
pmti.slot := position
}
}
/**
* @notice Gets the protocol status slot
*
* @return ps - the the protocol status slot
*/
function protocolStatus() internal pure returns (ProtocolStatus storage ps) {
bytes32 position = PROTOCOL_STATUS_POSITION;
assembly {
ps.slot := position
}
}
}{
"viaIR": false,
"optimizer": {
"enabled": true,
"runs": 100,
"details": {
"yul": true
}
},
"evmVersion": "shanghai",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_wNative","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessDenied","type":"error"},{"inputs":[],"name":"AddressesAndCalldataLengthMismatch","type":"error"},{"inputs":[],"name":"AdminOrAuthToken","type":"error"},{"inputs":[],"name":"AgentAddressMustBeUnique","type":"error"},{"inputs":[],"name":"AgentFeeAmountTooHigh","type":"error"},{"inputs":[],"name":"AlreadyInitialized","type":"error"},{"inputs":[],"name":"AmbiguousVoucherExpiry","type":"error"},{"inputs":[],"name":"AmountExceedsRangeOrNothingToBurn","type":"error"},{"inputs":[],"name":"ArrayLengthMismatch","type":"error"},{"inputs":[],"name":"AuthTokenMustBeUnique","type":"error"},{"inputs":[],"name":"BundleForTwinExists","type":"error"},{"inputs":[],"name":"BundleOfferMustBeUnique","type":"error"},{"inputs":[],"name":"BundleRequiresAtLeastOneTwinAndOneOffer","type":"error"},{"inputs":[],"name":"BundleTwinMustBeUnique","type":"error"},{"inputs":[],"name":"BuyerAddressMustBeUnique","type":"error"},{"inputs":[],"name":"CannotCommit","type":"error"},{"inputs":[],"name":"CannotRemoveDefaultRecipient","type":"error"},{"inputs":[],"name":"ClerkDeprecated","type":"error"},{"inputs":[],"name":"CloneCreationFailed","type":"error"},{"inputs":[],"name":"DRFeeMutualizerCannotProvideCoverage","type":"error"},{"inputs":[],"name":"DRUnsupportedFee","type":"error"},{"inputs":[],"name":"DirectInitializationNotAllowed","type":"error"},{"inputs":[],"name":"DisputeHasExpired","type":"error"},{"inputs":[],"name":"DisputePeriodHasElapsed","type":"error"},{"inputs":[],"name":"DisputePeriodNotElapsed","type":"error"},{"inputs":[],"name":"DisputeResolverAddressMustBeUnique","type":"error"},{"inputs":[],"name":"DisputeResolverFeeNotFound","type":"error"},{"inputs":[],"name":"DisputeStillValid","type":"error"},{"inputs":[],"name":"DuplicateDisputeResolverFees","type":"error"},{"inputs":[],"name":"EscalationNotAllowed","type":"error"},{"inputs":[],"name":"ExchangeAlreadyExists","type":"error"},{"inputs":[],"name":"ExchangeForOfferExists","type":"error"},{"inputs":[],"name":"ExchangeIdInReservedRange","type":"error"},{"inputs":[],"name":"ExchangeIsNotInAFinalState","type":"error"},{"inputs":[],"name":"ExternalCallFailed","type":"error"},{"inputs":[],"name":"FeeAmountTooHigh","type":"error"},{"inputs":[],"name":"FeeTableAssetNotSupported","type":"error"},{"inputs":[],"name":"FunctionNotAllowlisted","type":"error"},{"inputs":[],"name":"GroupHasCondition","type":"error"},{"inputs":[],"name":"GroupHasNoCondition","type":"error"},{"inputs":[],"name":"IncomingVoucherAlreadySet","type":"error"},{"inputs":[],"name":"InexistentAllowedSellersList","type":"error"},{"inputs":[],"name":"InexistentDisputeResolverFees","type":"error"},{"inputs":[],"name":"InsufficientAvailableFunds","type":"error"},{"inputs":[],"name":"InsufficientTwinSupplyToCoverBundleOffers","type":"error"},{"inputs":[],"name":"InsufficientValueReceived","type":"error"},{"inputs":[],"name":"InteractionNotAllowed","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidAgentFeePercentage","type":"error"},{"inputs":[],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidAmountToMint","type":"error"},{"inputs":[],"name":"InvalidAuthTokenType","type":"error"},{"inputs":[],"name":"InvalidBuyerOfferFields","type":"error"},{"inputs":[],"name":"InvalidBuyerPercent","type":"error"},{"inputs":[],"name":"InvalidCollectionIndex","type":"error"},{"inputs":[],"name":"InvalidConditionParameters","type":"error"},{"inputs":[],"name":"InvalidConduitAddress","type":"error"},{"inputs":[],"name":"InvalidDisputePeriod","type":"error"},{"inputs":[],"name":"InvalidDisputeResolver","type":"error"},{"inputs":[],"name":"InvalidDisputeTimeout","type":"error"},{"inputs":[],"name":"InvalidEscalationPeriod","type":"error"},{"inputs":[],"name":"InvalidFeePercentage","type":"error"},{"inputs":[],"name":"InvalidFunctionName","type":"error"},{"inputs":[],"name":"InvalidOffer","type":"error"},{"inputs":[],"name":"InvalidOfferCreator","type":"error"},{"inputs":[],"name":"InvalidOfferPenalty","type":"error"},{"inputs":[],"name":"InvalidOfferPeriod","type":"error"},{"inputs":[],"name":"InvalidPriceDiscovery","type":"error"},{"inputs":[],"name":"InvalidPriceDiscoveryPrice","type":"error"},{"inputs":[],"name":"InvalidPriceType","type":"error"},{"inputs":[],"name":"InvalidQuantityAvailable","type":"error"},{"inputs":[],"name":"InvalidRangeLength","type":"error"},{"inputs":[],"name":"InvalidRangeStart","type":"error"},{"inputs":[],"name":"InvalidRedemptionPeriod","type":"error"},{"inputs":[],"name":"InvalidResolutionPeriod","type":"error"},{"inputs":[],"name":"InvalidRoyaltyFee","type":"error"},{"inputs":[],"name":"InvalidRoyaltyInfo","type":"error"},{"inputs":[],"name":"InvalidRoyaltyPercentage","type":"error"},{"inputs":[],"name":"InvalidRoyaltyRecipient","type":"error"},{"inputs":[],"name":"InvalidRoyaltyRecipientId","type":"error"},{"inputs":[],"name":"InvalidSellerOfferFields","type":"error"},{"inputs":[],"name":"InvalidSignature","type":"error"},{"inputs":[],"name":"InvalidState","type":"error"},{"inputs":[],"name":"InvalidSupplyAvailable","type":"error"},{"inputs":[],"name":"InvalidTargeDisputeState","type":"error"},{"inputs":[],"name":"InvalidTargeExchangeState","type":"error"},{"inputs":[],"name":"InvalidToAddress","type":"error"},{"inputs":[],"name":"InvalidTokenAddress","type":"error"},{"inputs":[],"name":"InvalidTokenId","type":"error"},{"inputs":[],"name":"InvalidTwinProperty","type":"error"},{"inputs":[],"name":"InvalidTwinTokenRange","type":"error"},{"inputs":[],"name":"MaxCommitsReached","type":"error"},{"inputs":[],"name":"MustBeActive","type":"error"},{"inputs":[],"name":"NativeNotAllowed","type":"error"},{"inputs":[],"name":"NativeWrongAddress","type":"error"},{"inputs":[],"name":"NativeWrongAmount","type":"error"},{"inputs":[],"name":"NegativePriceNotAllowed","type":"error"},{"inputs":[],"name":"NoPendingUpdateForAccount","type":"error"},{"inputs":[],"name":"NoReservedRangeForOffer","type":"error"},{"inputs":[],"name":"NoSilentMintAllowed","type":"error"},{"inputs":[],"name":"NoSuchAgent","type":"error"},{"inputs":[],"name":"NoSuchBundle","type":"error"},{"inputs":[],"name":"NoSuchBuyer","type":"error"},{"inputs":[],"name":"NoSuchCollection","type":"error"},{"inputs":[],"name":"NoSuchDisputeResolver","type":"error"},{"inputs":[],"name":"NoSuchEntity","type":"error"},{"inputs":[],"name":"NoSuchExchange","type":"error"},{"inputs":[],"name":"NoSuchGroup","type":"error"},{"inputs":[],"name":"NoSuchOffer","type":"error"},{"inputs":[],"name":"NoSuchSeller","type":"error"},{"inputs":[],"name":"NoSuchTwin","type":"error"},{"inputs":[],"name":"NoTransferApproved","type":"error"},{"inputs":[],"name":"NoUpdateApplied","type":"error"},{"inputs":[],"name":"NonAscendingOrder","type":"error"},{"inputs":[],"name":"NonceUsedAlready","type":"error"},{"inputs":[],"name":"NotAdmin","type":"error"},{"inputs":[],"name":"NotAdminAndAssistant","type":"error"},{"inputs":[],"name":"NotAgentWallet","type":"error"},{"inputs":[],"name":"NotAssistant","type":"error"},{"inputs":[],"name":"NotAuthorized","type":"error"},{"inputs":[],"name":"NotBuyerOrSeller","type":"error"},{"inputs":[],"name":"NotBuyerWallet","type":"error"},{"inputs":[],"name":"NotDisputeResolverAssistant","type":"error"},{"inputs":[],"name":"NotOfferCreator","type":"error"},{"inputs":[],"name":"NotPaused","type":"error"},{"inputs":[],"name":"NotVoucherHolder","type":"error"},{"inputs":[],"name":"NothingToWithdraw","type":"error"},{"inputs":[],"name":"NothingUpdated","type":"error"},{"inputs":[],"name":"OfferExpiredOrVoided","type":"error"},{"inputs":[],"name":"OfferHasBeenVoided","type":"error"},{"inputs":[],"name":"OfferHasExpired","type":"error"},{"inputs":[],"name":"OfferMustBeActive","type":"error"},{"inputs":[],"name":"OfferMustBeUnique","type":"error"},{"inputs":[],"name":"OfferNotAvailable","type":"error"},{"inputs":[],"name":"OfferNotInBundle","type":"error"},{"inputs":[],"name":"OfferNotInGroup","type":"error"},{"inputs":[],"name":"OfferRangeAlreadyReserved","type":"error"},{"inputs":[],"name":"OfferSoldOut","type":"error"},{"inputs":[],"name":"OfferStillValid","type":"error"},{"inputs":[],"name":"PriceDoesNotCoverPenalty","type":"error"},{"inputs":[],"name":"PriceMismatch","type":"error"},{"inputs":[],"name":"ProtocolInitializationFailed","type":"error"},{"inputs":[],"name":"RecipientNotUnique","type":"error"},{"inputs":[],"name":"ReentrancyGuard","type":"error"},{"inputs":[{"internalType":"enum BosonTypes.PausableRegion","name":"region","type":"uint8"}],"name":"RegionPaused","type":"error"},{"inputs":[],"name":"RoyaltyRecipientIdsNotSorted","type":"error"},{"inputs":[],"name":"SameMutualizerAddress","type":"error"},{"inputs":[],"name":"SellerAddressMustBeUnique","type":"error"},{"inputs":[],"name":"SellerAlreadyApproved","type":"error"},{"inputs":[],"name":"SellerNotApproved","type":"error"},{"inputs":[],"name":"SellerParametersNotAllowed","type":"error"},{"inputs":[],"name":"SellerSaltNotUnique","type":"error"},{"inputs":[],"name":"SignatureValidationFailed","type":"error"},{"inputs":[],"name":"TokenAmountMismatch","type":"error"},{"inputs":[],"name":"TokenIdMandatory","type":"error"},{"inputs":[],"name":"TokenIdMismatch","type":"error"},{"inputs":[],"name":"TokenIdNotInConditionRange","type":"error"},{"inputs":[],"name":"TokenIdNotSet","type":"error"},{"inputs":[],"name":"TokenTransferFailed","type":"error"},{"inputs":[],"name":"TotalFeeExceedsLimit","type":"error"},{"inputs":[],"name":"TwinNotInBundle","type":"error"},{"inputs":[],"name":"TwinTransferUnsuccessful","type":"error"},{"inputs":[],"name":"TwinsAlreadyExist","type":"error"},{"inputs":[],"name":"UnauthorizedCallerUpdate","type":"error"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"UnexpectedDataReturned","type":"error"},{"inputs":[],"name":"UnexpectedERC721Received","type":"error"},{"inputs":[],"name":"UnsupportedMutualizer","type":"error"},{"inputs":[],"name":"UnsupportedToken","type":"error"},{"inputs":[],"name":"ValueZeroNotAllowed","type":"error"},{"inputs":[],"name":"VersionMustBeSet","type":"error"},{"inputs":[],"name":"VoucherExtensionNotValid","type":"error"},{"inputs":[],"name":"VoucherHasExpired","type":"error"},{"inputs":[],"name":"VoucherNotReceived","type":"error"},{"inputs":[],"name":"VoucherNotRedeemable","type":"error"},{"inputs":[],"name":"VoucherNotTransferred","type":"error"},{"inputs":[],"name":"VoucherStillValid","type":"error"},{"inputs":[],"name":"VoucherTransferNotAllowed","type":"error"},{"inputs":[],"name":"WalletOwnsVouchers","type":"error"},{"inputs":[],"name":"WrongCurrentVersion","type":"error"},{"inputs":[],"name":"WrongDefaultRecipient","type":"error"},{"inputs":[],"name":"ZeroDepositNotAllowed","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"buyerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"components":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"offerId","type":"uint256"},{"internalType":"uint256","name":"buyerId","type":"uint256"},{"internalType":"uint256","name":"finalizedDate","type":"uint256"},{"internalType":"enum BosonTypes.ExchangeState","name":"state","type":"uint8"},{"internalType":"address payable","name":"mutualizerAddress","type":"address"}],"indexed":false,"internalType":"struct BosonTypes.Exchange","name":"exchange","type":"tuple"},{"components":[{"internalType":"uint256","name":"committedDate","type":"uint256"},{"internalType":"uint256","name":"validUntilDate","type":"uint256"},{"internalType":"uint256","name":"redeemedDate","type":"uint256"},{"internalType":"bool","name":"expired","type":"bool"}],"indexed":false,"internalType":"struct BosonTypes.Voucher","name":"voucher","type":"tuple"},{"indexed":false,"internalType":"address","name":"executedBy","type":"address"}],"name":"BuyerCommitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"sellerId","type":"uint256"},{"components":[{"internalType":"uint256","name":"collectionIndex","type":"uint256"},{"components":[{"internalType":"address payable[]","name":"recipients","type":"address[]"},{"internalType":"uint256[]","name":"bps","type":"uint256[]"}],"internalType":"struct BosonTypes.RoyaltyInfo","name":"royaltyInfo","type":"tuple"},{"internalType":"address payable","name":"mutualizerAddress","type":"address"}],"indexed":false,"internalType":"struct BosonTypes.SellerOfferParams","name":"sellerParams","type":"tuple"},{"indexed":false,"internalType":"address","name":"executedBy","type":"address"}],"name":"BuyerInitiatedOfferSetSellerParams","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":false,"internalType":"enum BosonTypes.GatingType","name":"gating","type":"uint8"},{"indexed":true,"internalType":"address","name":"buyerAddress","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"commitCount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"maxCommits","type":"uint256"}],"name":"ConditionalCommitAuthorized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"feeAmount","type":"uint256"},{"indexed":true,"internalType":"address","name":"mutualizerAddress","type":"address"},{"indexed":false,"internalType":"address","name":"executedBy","type":"address"}],"name":"DRFeeRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"returnAmount","type":"uint256"},{"indexed":true,"internalType":"address","name":"mutualizerAddress","type":"address"},{"indexed":false,"internalType":"address","name":"executedBy","type":"address"}],"name":"DRFeeReturnFailed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"returnAmount","type":"uint256"},{"indexed":true,"internalType":"address","name":"mutualizerAddress","type":"address"},{"indexed":false,"internalType":"address","name":"executedBy","type":"address"}],"name":"DRFeeReturned","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"buyerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":false,"internalType":"address","name":"executedBy","type":"address"}],"name":"ExchangeCompleted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"entityId","type":"uint256"},{"indexed":true,"internalType":"address","name":"executedBy","type":"address"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FundsDeposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"entityId","type":"uint256"},{"indexed":true,"internalType":"address","name":"exchangeToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":true,"internalType":"address","name":"executedBy","type":"address"}],"name":"FundsEncumbered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"entityId","type":"uint256"},{"indexed":true,"internalType":"address","name":"exchangeToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"address","name":"executedBy","type":"address"}],"name":"FundsReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"sellerId","type":"uint256"},{"indexed":true,"internalType":"address","name":"withdrawnTo","type":"address"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"address","name":"executedBy","type":"address"}],"name":"FundsWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":true,"internalType":"address","name":"exchangeToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":true,"internalType":"address","name":"executedBy","type":"address"}],"name":"ProtocolFeeCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"sellerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"components":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"offerId","type":"uint256"},{"internalType":"uint256","name":"buyerId","type":"uint256"},{"internalType":"uint256","name":"finalizedDate","type":"uint256"},{"internalType":"enum BosonTypes.ExchangeState","name":"state","type":"uint8"},{"internalType":"address payable","name":"mutualizerAddress","type":"address"}],"indexed":false,"internalType":"struct BosonTypes.Exchange","name":"exchange","type":"tuple"},{"components":[{"internalType":"uint256","name":"committedDate","type":"uint256"},{"internalType":"uint256","name":"validUntilDate","type":"uint256"},{"internalType":"uint256","name":"redeemedDate","type":"uint256"},{"internalType":"bool","name":"expired","type":"bool"}],"indexed":false,"internalType":"struct BosonTypes.Voucher","name":"voucher","type":"tuple"},{"indexed":false,"internalType":"address","name":"executedBy","type":"address"}],"name":"SellerCommitted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":true,"internalType":"address","name":"executedBy","type":"address"}],"name":"VoucherCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":true,"internalType":"address","name":"executedBy","type":"address"}],"name":"VoucherExpired","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"validUntil","type":"uint256"},{"indexed":true,"internalType":"address","name":"executedBy","type":"address"}],"name":"VoucherExtended","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":true,"internalType":"address","name":"executedBy","type":"address"}],"name":"VoucherRedeemed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":true,"internalType":"address","name":"executedBy","type":"address"}],"name":"VoucherRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"offerId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"exchangeId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"newBuyerId","type":"uint256"},{"indexed":false,"internalType":"address","name":"executedBy","type":"address"}],"name":"VoucherTransferred","type":"event"},{"inputs":[],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address payable","name":"_buyer","type":"address"},{"internalType":"uint256","name":"_tokenId","type":"uint256"},{"components":[{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"enum BosonTypes.Side","name":"side","type":"uint8"},{"internalType":"address","name":"priceDiscoveryContract","type":"address"},{"internalType":"address","name":"conduit","type":"address"},{"internalType":"bytes","name":"priceDiscoveryData","type":"bytes"}],"internalType":"struct BosonTypes.PriceDiscovery","name":"_priceDiscovery","type":"tuple"}],"name":"sequentialCommitToOffer","outputs":[],"stateMutability":"payable","type":"function"}]Contract Creation Code
60a060405234801561000f575f80fd5b5060405162001de438038062001de48339810160408190526100309161006a565b806001600160a01b0381166100585760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b031660805250610097565b5f6020828403121561007a575f80fd5b81516001600160a01b0381168114610090575f80fd5b9392505050565b608051611d2d620000b75f395f818161032c0152610d3c0152611d2d5ff3fe608060405260043610610028575f3560e01c806334780cc61461002c5780638129fc1c14610041575b5f80fd5b61003f61003a3660046117fe565b610055565b005b34801561004c575f80fd5b5061003f61055d565b61005f6008610625565b6100696005610625565b610073600e610625565b5f61007c610673565b905060028160010154036100a3576040516345f5ce8b60e11b815260040160405180910390fd5b600260018201556001600160a01b0384166100d15760405163e6c4247b60e01b815260040160405180910390fd5b6001600160801b0383165f806100e78382610697565b915091508060010154421115610110576040516359c99d7160e01b815260040160405180910390fd5b61013d6040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b60028301548082525f90819061015290610721565b600190810154908701546001600160a01b03909116935091505f905061017782610754565b9150506101878a828b868f610783565b602085015260068101546001600160a01b03165f80806101a5610982565b6013015f8c81526020019081526020015f2090506101c78489602001516109ab565b60408901525f6101d78782610a14565b5060808b015260208a0151909150612710906101f560018401610af6565b6101ff919061186d565b6102099190611884565b60608a0181905260208a015160408b015190925061022791906118a3565b11156102465760405163324ac3e360e01b815260040160405180910390fd5b80545f90801561027a57826001820381548110610265576102656118b6565b905f5260205f20906005020160010154610280565b86600201545b91505061029d818a604001518b606001518c602001510303610b3b565b6020808b0180518554600181810188555f888152949094208e51600590920201908155915192820183905560408d0151600283015560608d0151600383015560808d01516004909201919091559190910394508481039350158015915061030b57506001600160a01b038416155b1561038c576020880151604051632e1a7d4d60e01b815260048101919091527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d906024015f604051808303815f87803b158015610375575f80fd5b505af1158015610387573d5f803e3d5ffd5b505050505b811561039d5761039d848884610b52565b506103a6610bef565b60028901545f6103b4610c12565b60208a01519091501561046657846001600160a01b0316816001600160a01b0316837f862dfcd9710943e66ad8f1f01a99cc98ab5612a09e62ecc68f63fe2e0f86cb0e8c6020015160405161040b91815260200190565b60405180910390a4806001600160a01b0316856001600160a01b0316837f8080d30eb13935d67dfdc606fa5e4170aa03ffdfaf40136ef3fa4355c88b19f98c6020015160405161045d91815260200190565b60405180910390a45b8215610505578851604080518581526001600160a01b038481166020830152881692918f917fea32da6ba3310a019ad2eba7e0b3063c1dbe129dbc3bfa2638b5d3165183e6ae910160405180910390a48851604080518581526001600160a01b03848116602083015280891693908c169290917f046262a2c36feade253f14bedd4cc14f1027bb71665b45a9b206a8fa5169663c910160405180910390a45b8b82887fb52015a0ea2e0345baee81bf183c410328b8f8d0cfd380c43006bb84b78fc1008e8e8660405161053b939291906118de565b60405180910390a4505060019a8b019a909a5550505050505050505050505050565b631a3c066360e11b5f61056e610c52565b6001600160e01b031983165f90815260028201602052604090205490915060ff16156105ac5760405162dc149f60e41b815260040160405180910390fd5b6001600160e01b031982165f9081526002820160205260409020805460ff19166001179055610621631a3c066360e11b6001600160e01b0319165f9081527fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131f602052604090208054600160ff19909116179055565b5050565b5f81600e811115610638576106386118ca565b6001901b90508081610648610673565b5416036106215781604051633ff588ab60e01b815260040161066a919061197b565b60405180910390fd5b7fe7ad30265b8084c731e610579d091ebe2886115e8a5cacb6b704e4392f48b2c190565b5f805f6106a385610c5b565b93509050806106c55760405163437d9dd360e01b815260040160405180910390fd5b8360058111156106d7576106d76118ca565b600484015460ff1660058111156106f0576106f06118ca565b1461070e5760405163baf3f0f760e01b815260040160405180910390fd5b61071785610c8d565b9150509250929050565b5f8061072b610982565b5f848152600a91909101602052604090209050821580159061074d5750805483145b9150915091565b5f8061075e610982565b5f848152602091909152604090209050821580159061074d5750805483149150915091565b5f61078e600d610625565b5f61079f6060860160408701611995565b6001600160a01b031614806107c057506107bc60808501856119b0565b1590505b156107de57604051631d733b6360e31b815260040160405180910390fd5b60026107f06040860160208701611a0d565b6002811115610801576108016118ca565b1415801561082657505f61081b6080860160608701611995565b6001600160a01b0316145b156108445760405163593861a760e11b815260040160405180910390fd5b5f6108787f612ef4010290807451b703920dc633bec38eb4e2d0b1fda71d2a122f1b61c7ca876001015488600a0154610ca8565b905080610883610c52565b60060180546001600160a01b0319166001600160a01b03929092169190911790555f6108b56040870160208801611a0d565b60028111156108c6576108c66118ca565b036108f157855460068701546108ea9189916001600160a01b031688888887610d19565b9150610953565b60016109036040870160208801611a0d565b6002811115610914576109146118ca565b036109355760068601546108ea9088906001600160a01b0316878785610f26565b60068601546109509088906001600160a01b03168784611082565b91505b856004015482101561097857604051632fdad8ad60e01b815260040160405180910390fd5b5095945050505050565b7fc973828674331e26e5b526db986992b6e682e76403c37e06ee7953caf0e663c790565b905090565b5f6109b46111e7565b600101546001600160a01b03908116908416036109f357507fcc61e6c6f125f3893e1d1fcb0479f4a7b78046e243532c7c469d64eccea5822254610a0e565b5f6109fe848461120b565b9050610a0a838261134b565b9150505b92915050565b5f805f808415610a53575f80610a2988610c5b565b9150915081610a4b5760405163437d9dd360e01b815260040160405180910390fd5b600101549650505b5f610a5c610982565b5f8881526020828152604080832060018101548452600985018352908320600401548b845291849052600b810180546001600160a01b039093169750955092935090819003610abe576040516328f1b7df60e01b815260040160405180910390fd5b610ac9600182611a26565b9550838681548110610add57610add6118b6565b905f5260205f2090600202019650505050509250925092565b80545f90815b81811015610b3457838181548110610b1657610b166118b6565b905f5260205f20015483610b2a91906118a3565b9250600101610afc565b5050919050565b5f818310610b495781610b4b565b825b9392505050565b6001600160a01b038316610bd6575f826001600160a01b0316826040515f6040518083038185875af1925050503d805f8114610ba9576040519150601f19603f3d011682016040523d82523d5f602084013e610bae565b606091505b5050905080610bd05760405163022e258160e11b815260040160405180910390fd5b50505050565b610bea6001600160a01b0384168383611381565b505050565b5f610bf8610c52565b5f600582015560060180546001600160a01b031916905550565b5f363330148015610c24575060148110155b15610c4b57610c39366013198301815f611a39565b610c4291611a60565b60601c91505090565b3391505090565b5f6109a6610673565b5f80610c65610982565b5f848152600591909101602052604090209050821580159061074d5750805483149150915091565b5f610c96610982565b5f928352600601602052506040902090565b5f8115610cf7575f8381526022850160205260409020610cc9600184611a26565b81548110610cd957610cd96118b6565b5f9182526020909120600290910201546001600160a01b0316610d11565b5f8381526011850160205260409020546001600160a01b03165b949350505050565b5f80610d236111e7565b600401546001600160a01b0390811691508716610d5e577f000000000000000000000000000000000000000000000000000000000000000096505b610d698787356113e4565b610d7587828835610b52565b806001600160a01b031663dc871858888886610d8f610c12565b6040518563ffffffff1660e01b8152600401610dae9493929190611b75565b6020604051808303815f875af1158015610dca573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610dee9190611baf565b9150610df98961143b565b98508760808a901c14610e1f57604051633101a57160e01b815260040160405180910390fd5b6040516331a9108f60e11b8152600481018a90526001600160a01b038083169190851690636352211e90602401602060405180830381865afa158015610e67573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e8b9190611bc6565b6001600160a01b031614610eb25760405163fe585ebf60e01b815260040160405180910390fd5b604051632142170760e11b81526001600160a01b038416906342842e0e90610ee290849088908e90600401611be1565b5f604051808303815f87803b158015610ef9575f80fd5b505af1158015610f0b573d5f803e3d5ffd5b50505050610f1a8786846114a5565b50979650505050505050565b5f855f03610f475760405163659bc02960e11b815260040160405180910390fd5b5f610f50610c12565b9050806001600160a01b0316846001600160a01b031614610f84576040516305deec9d60e31b815260040160405180910390fd5b5f610f8d6111e7565b6004908101546040516323b872dd60e01b81526001600160a01b039182169350908616916323b872dd91610fc791899186918e9101611be1565b5f604051808303815f87803b158015610fde575f80fd5b505af1158015610ff0573d5f803e3d5ffd5b5050604051630a900abf60e41b81526001600160a01b038416925063a900abf09150349061102a908c908c908c908c908c90600401611c05565b60206040518083038185885af1158015611046573d5f803e3d5ffd5b50505050506040513d601f19601f8201168201806040525081019061106b9190611baf565b92506110768861143b565b50505095945050505050565b5f845f036110a35760405163659bc02960e11b815260040160405180910390fd5b6040516331a9108f60e11b8152600481018690525f906001600160a01b03841690636352211e90602401602060405180830381865afa1580156110e8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061110c9190611bc6565b905061111e6060850160408601611995565b6001600160a01b0316816001600160a01b03161461114f576040516305deec9d60e31b815260040160405180910390fd5b5f6111586111e7565b60049081015460405163fe4b57bf60e01b81526001600160a01b039091169250829163fe4b57bf913491611190918b918b9101611c46565b60206040518083038185885af11580156111ac573d5f803e3d5ffd5b50505050506040513d601f19601f820116820180604052508101906111d19190611baf565b92506111dc8761143b565b505050949350505050565b7fcfefadf1e49ed481e9aa8b96a2b3ebd4043faf5a3594be1a1ff7f364fce11e7990565b5f6112146111e7565b600101546001600160a01b039081169084160361124457604051630167f5d160e11b815260040160405180910390fd5b6001600160a01b0383165f9081527fcc61e6c6f125f3893e1d1fcb0479f4a7b78046e243532c7c469d64eccea58224602090815260408083207fcc61e6c6f125f3893e1d1fcb0479f4a7b78046e243532c7c469d64eccea5822590925290912081547fcc61e6c6f125f3893e1d1fcb0479f4a7b78046e243532c7c469d64eccea58221929190801561133f575f5b6001820381101561132d578381815481106112ef576112ef6118b6565b905f5260205f200154871161132557828181548110611310576113106118b6565b905f5260205f20015495505050505050610a0e565b6001016112d2565b828181548110611310576113106118b6565b50509054949350505050565b5f612710820361135c575081610a0e565b815f0361136a57505f610a0e565b612710611377838561186d565b610b4b9190611884565b6040516001600160a01b038316602482015260448101829052610bea90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526115c4565b6001600160a01b038216611412578034146106215760405163e5bd963960e01b815260040160405180910390fd5b3415611431576040516320f2ada960e11b815260040160405180910390fd5b6106218282611697565b5f80611445610c52565b90508215611476578060050154831461147157604051633101a57160e01b815260040160405180910390fd5b61147e565b806005015492505b825f0361149e5760405163295fa13d60e11b815260040160405180910390fd5b5090919050565b8015610bea576040516370a0823160e01b81523060048201525f906001600160a01b038516906370a0823190602401602060405180830381865afa1580156114ef573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115139190611baf565b905061152a6001600160a01b0385168430856116a9565b6040516370a0823160e01b81523060048201525f906001600160a01b038616906370a0823190602401602060405180830381865afa15801561156e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115929190611baf565b90508261159f8383611a26565b146115bd5760405163e5bd963960e01b815260040160405180910390fd5b5050505050565b5f611618826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166116ca9092919063ffffffff16565b905080515f14806116385750808060200190518101906116389190611c69565b610bea5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161066a565b610621826116a3610c12565b836114a5565b610bd0846323b872dd60e01b8585856040516024016113ad93929190611be1565b6060610d1184845f85855f80866001600160a01b031685876040516116ef9190611caa565b5f6040518083038185875af1925050503d805f8114611729576040519150601f19603f3d011682016040523d82523d5f602084013e61172e565b606091505b509150915061173f8783838761174a565b979650505050505050565b606083156117b85782515f036117b1576001600160a01b0385163b6117b15760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161066a565b5081610d11565b610d1183838151156117cd5781518083602001fd5b8060405162461bcd60e51b815260040161066a9190611cc5565b6001600160a01b03811681146117fb575f80fd5b50565b5f805f60608486031215611810575f80fd5b833561181b816117e7565b925060208401359150604084013567ffffffffffffffff81111561183d575f80fd5b840160a0818703121561184e575f80fd5b809150509250925092565b634e487b7160e01b5f52601160045260245ffd5b8082028115828204841417610a0e57610a0e611859565b5f8261189e57634e487b7160e01b5f52601260045260245ffd5b500490565b80820180821115610a0e57610a0e611859565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b83548152600184015460208201526002840154604082015260038401546060820152600484015461016082019060ff81166006811061191f5761191f6118ca565b608084015260081c6001600160a01b031660a083015261196660c08301858054825260018101546020830152600281015460408301526003015460ff161515606090910152565b6001600160a01b038316610140830152610d11565b60208101600f831061198f5761198f6118ca565b91905290565b5f602082840312156119a5575f80fd5b8135610b4b816117e7565b5f808335601e198436030181126119c5575f80fd5b83018035915067ffffffffffffffff8211156119df575f80fd5b6020019150368190038213156119f3575f80fd5b9250929050565b803560038110611a08575f80fd5b919050565b5f60208284031215611a1d575f80fd5b610b4b826119fa565b81810381811115610a0e57610a0e611859565b5f8085851115611a47575f80fd5b83861115611a53575f80fd5b5050820193919092039150565b6bffffffffffffffffffffffff198135818116916014851015611a8d5780818660140360031b1b83161692505b505092915050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b803582525f611ace602083016119fa565b60038110611ade57611ade6118ca565b60208401526040820135611af1816117e7565b6001600160a01b039081166040850152606083013590611b10826117e7565b166060840152608082013536839003601e19018112611b2d575f80fd5b820160208101903567ffffffffffffffff811115611b49575f80fd5b803603821315611b57575f80fd5b60a06080860152611b6c60a086018284611a95565b95945050505050565b5f60018060a01b03808716835260806020840152611b966080840187611abd565b9481166040840152929092166060909101525092915050565b5f60208284031215611bbf575f80fd5b5051919050565b5f60208284031215611bd6575f80fd5b8151610b4b816117e7565b6001600160a01b039384168152919092166020820152604081019190915260600190565b8581525f60018060a01b03808716602084015260a06040840152611c2c60a0840187611abd565b948116606084015292909216608090910152509392505050565b6001600160a01b03831681526040602082018190525f90610d1190830184611abd565b5f60208284031215611c79575f80fd5b81518015158114610b4b575f80fd5b5f5b83811015611ca2578181015183820152602001611c8a565b50505f910152565b5f8251611cbb818460208701611c88565b9190910192915050565b602081525f8251806020840152611ce3816040850160208701611c88565b601f01601f1916919091016040019291505056fea2646970667358221220620b243be25a07d053cb20bf3f52c058e35053bc4cd7c0ccad647b70315e2e1f64736f6c63430008160033000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Deployed Bytecode
0x608060405260043610610028575f3560e01c806334780cc61461002c5780638129fc1c14610041575b5f80fd5b61003f61003a3660046117fe565b610055565b005b34801561004c575f80fd5b5061003f61055d565b61005f6008610625565b6100696005610625565b610073600e610625565b5f61007c610673565b905060028160010154036100a3576040516345f5ce8b60e11b815260040160405180910390fd5b600260018201556001600160a01b0384166100d15760405163e6c4247b60e01b815260040160405180910390fd5b6001600160801b0383165f806100e78382610697565b915091508060010154421115610110576040516359c99d7160e01b815260040160405180910390fd5b61013d6040518060a001604052805f81526020015f81526020015f81526020015f81526020015f81525090565b60028301548082525f90819061015290610721565b600190810154908701546001600160a01b03909116935091505f905061017782610754565b9150506101878a828b868f610783565b602085015260068101546001600160a01b03165f80806101a5610982565b6013015f8c81526020019081526020015f2090506101c78489602001516109ab565b60408901525f6101d78782610a14565b5060808b015260208a0151909150612710906101f560018401610af6565b6101ff919061186d565b6102099190611884565b60608a0181905260208a015160408b015190925061022791906118a3565b11156102465760405163324ac3e360e01b815260040160405180910390fd5b80545f90801561027a57826001820381548110610265576102656118b6565b905f5260205f20906005020160010154610280565b86600201545b91505061029d818a604001518b606001518c602001510303610b3b565b6020808b0180518554600181810188555f888152949094208e51600590920201908155915192820183905560408d0151600283015560608d0151600383015560808d01516004909201919091559190910394508481039350158015915061030b57506001600160a01b038416155b1561038c576020880151604051632e1a7d4d60e01b815260048101919091527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031690632e1a7d4d906024015f604051808303815f87803b158015610375575f80fd5b505af1158015610387573d5f803e3d5ffd5b505050505b811561039d5761039d848884610b52565b506103a6610bef565b60028901545f6103b4610c12565b60208a01519091501561046657846001600160a01b0316816001600160a01b0316837f862dfcd9710943e66ad8f1f01a99cc98ab5612a09e62ecc68f63fe2e0f86cb0e8c6020015160405161040b91815260200190565b60405180910390a4806001600160a01b0316856001600160a01b0316837f8080d30eb13935d67dfdc606fa5e4170aa03ffdfaf40136ef3fa4355c88b19f98c6020015160405161045d91815260200190565b60405180910390a45b8215610505578851604080518581526001600160a01b038481166020830152881692918f917fea32da6ba3310a019ad2eba7e0b3063c1dbe129dbc3bfa2638b5d3165183e6ae910160405180910390a48851604080518581526001600160a01b03848116602083015280891693908c169290917f046262a2c36feade253f14bedd4cc14f1027bb71665b45a9b206a8fa5169663c910160405180910390a45b8b82887fb52015a0ea2e0345baee81bf183c410328b8f8d0cfd380c43006bb84b78fc1008e8e8660405161053b939291906118de565b60405180910390a4505060019a8b019a909a5550505050505050505050505050565b631a3c066360e11b5f61056e610c52565b6001600160e01b031983165f90815260028201602052604090205490915060ff16156105ac5760405162dc149f60e41b815260040160405180910390fd5b6001600160e01b031982165f9081526002820160205260409020805460ff19166001179055610621631a3c066360e11b6001600160e01b0319165f9081527fc8fcad8db84d3cc18b4c41d551ea0ee66dd599cde068d998e57d5e09332c131f602052604090208054600160ff19909116179055565b5050565b5f81600e811115610638576106386118ca565b6001901b90508081610648610673565b5416036106215781604051633ff588ab60e01b815260040161066a919061197b565b60405180910390fd5b7fe7ad30265b8084c731e610579d091ebe2886115e8a5cacb6b704e4392f48b2c190565b5f805f6106a385610c5b565b93509050806106c55760405163437d9dd360e01b815260040160405180910390fd5b8360058111156106d7576106d76118ca565b600484015460ff1660058111156106f0576106f06118ca565b1461070e5760405163baf3f0f760e01b815260040160405180910390fd5b61071785610c8d565b9150509250929050565b5f8061072b610982565b5f848152600a91909101602052604090209050821580159061074d5750805483145b9150915091565b5f8061075e610982565b5f848152602091909152604090209050821580159061074d5750805483149150915091565b5f61078e600d610625565b5f61079f6060860160408701611995565b6001600160a01b031614806107c057506107bc60808501856119b0565b1590505b156107de57604051631d733b6360e31b815260040160405180910390fd5b60026107f06040860160208701611a0d565b6002811115610801576108016118ca565b1415801561082657505f61081b6080860160608701611995565b6001600160a01b0316145b156108445760405163593861a760e11b815260040160405180910390fd5b5f6108787f612ef4010290807451b703920dc633bec38eb4e2d0b1fda71d2a122f1b61c7ca876001015488600a0154610ca8565b905080610883610c52565b60060180546001600160a01b0319166001600160a01b03929092169190911790555f6108b56040870160208801611a0d565b60028111156108c6576108c66118ca565b036108f157855460068701546108ea9189916001600160a01b031688888887610d19565b9150610953565b60016109036040870160208801611a0d565b6002811115610914576109146118ca565b036109355760068601546108ea9088906001600160a01b0316878785610f26565b60068601546109509088906001600160a01b03168784611082565b91505b856004015482101561097857604051632fdad8ad60e01b815260040160405180910390fd5b5095945050505050565b7fc973828674331e26e5b526db986992b6e682e76403c37e06ee7953caf0e663c790565b905090565b5f6109b46111e7565b600101546001600160a01b03908116908416036109f357507fcc61e6c6f125f3893e1d1fcb0479f4a7b78046e243532c7c469d64eccea5822254610a0e565b5f6109fe848461120b565b9050610a0a838261134b565b9150505b92915050565b5f805f808415610a53575f80610a2988610c5b565b9150915081610a4b5760405163437d9dd360e01b815260040160405180910390fd5b600101549650505b5f610a5c610982565b5f8881526020828152604080832060018101548452600985018352908320600401548b845291849052600b810180546001600160a01b039093169750955092935090819003610abe576040516328f1b7df60e01b815260040160405180910390fd5b610ac9600182611a26565b9550838681548110610add57610add6118b6565b905f5260205f2090600202019650505050509250925092565b80545f90815b81811015610b3457838181548110610b1657610b166118b6565b905f5260205f20015483610b2a91906118a3565b9250600101610afc565b5050919050565b5f818310610b495781610b4b565b825b9392505050565b6001600160a01b038316610bd6575f826001600160a01b0316826040515f6040518083038185875af1925050503d805f8114610ba9576040519150601f19603f3d011682016040523d82523d5f602084013e610bae565b606091505b5050905080610bd05760405163022e258160e11b815260040160405180910390fd5b50505050565b610bea6001600160a01b0384168383611381565b505050565b5f610bf8610c52565b5f600582015560060180546001600160a01b031916905550565b5f363330148015610c24575060148110155b15610c4b57610c39366013198301815f611a39565b610c4291611a60565b60601c91505090565b3391505090565b5f6109a6610673565b5f80610c65610982565b5f848152600591909101602052604090209050821580159061074d5750805483149150915091565b5f610c96610982565b5f928352600601602052506040902090565b5f8115610cf7575f8381526022850160205260409020610cc9600184611a26565b81548110610cd957610cd96118b6565b5f9182526020909120600290910201546001600160a01b0316610d11565b5f8381526011850160205260409020546001600160a01b03165b949350505050565b5f80610d236111e7565b600401546001600160a01b0390811691508716610d5e577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc296505b610d698787356113e4565b610d7587828835610b52565b806001600160a01b031663dc871858888886610d8f610c12565b6040518563ffffffff1660e01b8152600401610dae9493929190611b75565b6020604051808303815f875af1158015610dca573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610dee9190611baf565b9150610df98961143b565b98508760808a901c14610e1f57604051633101a57160e01b815260040160405180910390fd5b6040516331a9108f60e11b8152600481018a90526001600160a01b038083169190851690636352211e90602401602060405180830381865afa158015610e67573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e8b9190611bc6565b6001600160a01b031614610eb25760405163fe585ebf60e01b815260040160405180910390fd5b604051632142170760e11b81526001600160a01b038416906342842e0e90610ee290849088908e90600401611be1565b5f604051808303815f87803b158015610ef9575f80fd5b505af1158015610f0b573d5f803e3d5ffd5b50505050610f1a8786846114a5565b50979650505050505050565b5f855f03610f475760405163659bc02960e11b815260040160405180910390fd5b5f610f50610c12565b9050806001600160a01b0316846001600160a01b031614610f84576040516305deec9d60e31b815260040160405180910390fd5b5f610f8d6111e7565b6004908101546040516323b872dd60e01b81526001600160a01b039182169350908616916323b872dd91610fc791899186918e9101611be1565b5f604051808303815f87803b158015610fde575f80fd5b505af1158015610ff0573d5f803e3d5ffd5b5050604051630a900abf60e41b81526001600160a01b038416925063a900abf09150349061102a908c908c908c908c908c90600401611c05565b60206040518083038185885af1158015611046573d5f803e3d5ffd5b50505050506040513d601f19601f8201168201806040525081019061106b9190611baf565b92506110768861143b565b50505095945050505050565b5f845f036110a35760405163659bc02960e11b815260040160405180910390fd5b6040516331a9108f60e11b8152600481018690525f906001600160a01b03841690636352211e90602401602060405180830381865afa1580156110e8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061110c9190611bc6565b905061111e6060850160408601611995565b6001600160a01b0316816001600160a01b03161461114f576040516305deec9d60e31b815260040160405180910390fd5b5f6111586111e7565b60049081015460405163fe4b57bf60e01b81526001600160a01b039091169250829163fe4b57bf913491611190918b918b9101611c46565b60206040518083038185885af11580156111ac573d5f803e3d5ffd5b50505050506040513d601f19601f820116820180604052508101906111d19190611baf565b92506111dc8761143b565b505050949350505050565b7fcfefadf1e49ed481e9aa8b96a2b3ebd4043faf5a3594be1a1ff7f364fce11e7990565b5f6112146111e7565b600101546001600160a01b039081169084160361124457604051630167f5d160e11b815260040160405180910390fd5b6001600160a01b0383165f9081527fcc61e6c6f125f3893e1d1fcb0479f4a7b78046e243532c7c469d64eccea58224602090815260408083207fcc61e6c6f125f3893e1d1fcb0479f4a7b78046e243532c7c469d64eccea5822590925290912081547fcc61e6c6f125f3893e1d1fcb0479f4a7b78046e243532c7c469d64eccea58221929190801561133f575f5b6001820381101561132d578381815481106112ef576112ef6118b6565b905f5260205f200154871161132557828181548110611310576113106118b6565b905f5260205f20015495505050505050610a0e565b6001016112d2565b828181548110611310576113106118b6565b50509054949350505050565b5f612710820361135c575081610a0e565b815f0361136a57505f610a0e565b612710611377838561186d565b610b4b9190611884565b6040516001600160a01b038316602482015260448101829052610bea90849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526115c4565b6001600160a01b038216611412578034146106215760405163e5bd963960e01b815260040160405180910390fd5b3415611431576040516320f2ada960e11b815260040160405180910390fd5b6106218282611697565b5f80611445610c52565b90508215611476578060050154831461147157604051633101a57160e01b815260040160405180910390fd5b61147e565b806005015492505b825f0361149e5760405163295fa13d60e11b815260040160405180910390fd5b5090919050565b8015610bea576040516370a0823160e01b81523060048201525f906001600160a01b038516906370a0823190602401602060405180830381865afa1580156114ef573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115139190611baf565b905061152a6001600160a01b0385168430856116a9565b6040516370a0823160e01b81523060048201525f906001600160a01b038616906370a0823190602401602060405180830381865afa15801561156e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115929190611baf565b90508261159f8383611a26565b146115bd5760405163e5bd963960e01b815260040160405180910390fd5b5050505050565b5f611618826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166116ca9092919063ffffffff16565b905080515f14806116385750808060200190518101906116389190611c69565b610bea5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161066a565b610621826116a3610c12565b836114a5565b610bd0846323b872dd60e01b8585856040516024016113ad93929190611be1565b6060610d1184845f85855f80866001600160a01b031685876040516116ef9190611caa565b5f6040518083038185875af1925050503d805f8114611729576040519150601f19603f3d011682016040523d82523d5f602084013e61172e565b606091505b509150915061173f8783838761174a565b979650505050505050565b606083156117b85782515f036117b1576001600160a01b0385163b6117b15760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161066a565b5081610d11565b610d1183838151156117cd5781518083602001fd5b8060405162461bcd60e51b815260040161066a9190611cc5565b6001600160a01b03811681146117fb575f80fd5b50565b5f805f60608486031215611810575f80fd5b833561181b816117e7565b925060208401359150604084013567ffffffffffffffff81111561183d575f80fd5b840160a0818703121561184e575f80fd5b809150509250925092565b634e487b7160e01b5f52601160045260245ffd5b8082028115828204841417610a0e57610a0e611859565b5f8261189e57634e487b7160e01b5f52601260045260245ffd5b500490565b80820180821115610a0e57610a0e611859565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b83548152600184015460208201526002840154604082015260038401546060820152600484015461016082019060ff81166006811061191f5761191f6118ca565b608084015260081c6001600160a01b031660a083015261196660c08301858054825260018101546020830152600281015460408301526003015460ff161515606090910152565b6001600160a01b038316610140830152610d11565b60208101600f831061198f5761198f6118ca565b91905290565b5f602082840312156119a5575f80fd5b8135610b4b816117e7565b5f808335601e198436030181126119c5575f80fd5b83018035915067ffffffffffffffff8211156119df575f80fd5b6020019150368190038213156119f3575f80fd5b9250929050565b803560038110611a08575f80fd5b919050565b5f60208284031215611a1d575f80fd5b610b4b826119fa565b81810381811115610a0e57610a0e611859565b5f8085851115611a47575f80fd5b83861115611a53575f80fd5b5050820193919092039150565b6bffffffffffffffffffffffff198135818116916014851015611a8d5780818660140360031b1b83161692505b505092915050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b803582525f611ace602083016119fa565b60038110611ade57611ade6118ca565b60208401526040820135611af1816117e7565b6001600160a01b039081166040850152606083013590611b10826117e7565b166060840152608082013536839003601e19018112611b2d575f80fd5b820160208101903567ffffffffffffffff811115611b49575f80fd5b803603821315611b57575f80fd5b60a06080860152611b6c60a086018284611a95565b95945050505050565b5f60018060a01b03808716835260806020840152611b966080840187611abd565b9481166040840152929092166060909101525092915050565b5f60208284031215611bbf575f80fd5b5051919050565b5f60208284031215611bd6575f80fd5b8151610b4b816117e7565b6001600160a01b039384168152919092166020820152604081019190915260600190565b8581525f60018060a01b03808716602084015260a06040840152611c2c60a0840187611abd565b948116606084015292909216608090910152509392505050565b6001600160a01b03831681526040602082018190525f90610d1190830184611abd565b5f60208284031215611c79575f80fd5b81518015158114610b4b575f80fd5b5f5b83811015611ca2578181015183820152602001611c8a565b50505f910152565b5f8251611cbb818460208701611c88565b9190910192915050565b602081525f8251806020840152611ce3816040850160208701611c88565b601f01601f1916919091016040019291505056fea2646970667358221220620b243be25a07d053cb20bf3f52c058e35053bc4cd7c0ccad647b70315e2e1f64736f6c63430008160033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
-----Decoded View---------------
Arg [0] : _wNative (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.