// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {IAggregator} from "src/marketplace/interfaces/IAggregator.sol";
import {MarketplaceTypes} from "src/marketplace/MarketplaceTypes.sol";
/// @notice Contract that provides helper functions to handle Chainlink Aggregator results and related operations.
contract AggregatorHelper {
error AggregatorAnswerIsNegative();
error AggregatorAnswerIsStale();
/// @dev Used to obtain the rate from an aggregator.
/// @param _aggregator The aggregator used to obtain the rate.
/// @param _staleTolerance The tolerated amount of seconds since the last update of the rate.
/// @return The rate obtained from the aggregator, normalized to 18 decimals.
function _getRateFromAggregator(IAggregator _aggregator, uint256 _staleTolerance) internal view returns (int256) {
// Obtains rate values from the aggregator.
(, int256 rate,, uint256 updatedAt,) = _aggregator.latestRoundData();
// If the rate is negative, reverts.
// This should not happen with currency aggregators but it's a good practice to check.
if (rate < 0) {
revert AggregatorAnswerIsNegative();
}
// If the result provided by the aggregator is too old, reverts.
if (updatedAt < (block.timestamp - _staleTolerance)) {
revert AggregatorAnswerIsStale();
}
// Obtains the number of decimals the rate has been returned as from the aggregator.
uint8 decimals = _aggregator.decimals();
// Normalizes the rate to 18 decimals.
rate = rate * int256(10 ** (18 - decimals));
return rate;
}
/// @dev Uses the original value in USD of the asset and updates it to MANA using the provided rate.
/// Also updates the contract address to the MANA address given that it is the asset that will be transferred.
function _updateAssetWithConvertedMANAPrice(MarketplaceTypes.Asset memory _asset, address _manaAddress, int256 _manaUsdRate)
internal
pure
{
// Update the asset contract address to be MANA.
_asset.contractAddress = _manaAddress;
// Update the asset value to be the amount of MANA to be transferred.
_asset.value = _asset.value * 1e18 / uint256(_manaUsdRate);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
/// @notice Types used by many contracts in this project.
abstract contract CommonTypes {
/// @notice Schema of an external check.
/// This is used to verify that certain external requirements are met.
/// @param contractAddress The address of the contract to call.
/// @param selector The selector of the function to call.
/// @param value The value to pass to the function.
/// @param required If the check is required or not.
struct ExternalCheck {
address contractAddress;
bytes4 selector;
bytes value;
bool required;
}
/// @notice Schema of a check.
/// This is used to verify that certain requirements are met.
/// @param uses The number of times the signature can be used.
/// @param expiration The expiration date of the signature.
/// @param effective The effective date of the signature.
/// @param salt A value used to make the signature unique.
/// @param contractSignatureIndex The contract signature index required to validate the signature.
/// @param signerSignatureIndex The signer signature index required to validate the signature.
/// @param allowedRoot The Merkle Root of the allowed addresses. If empty, no check is performed.
/// @param allowedProof The Merkle Proof that validates that the caller is allowed. Is not validated in the signature given that it is data used by the caller.
/// @param externalChecks The external checks to verify.
struct Checks {
uint256 uses;
uint256 expiration;
uint256 effective;
bytes32 salt;
uint256 contractSignatureIndex;
uint256 signerSignatureIndex;
bytes32 allowedRoot;
bytes32[] allowedProof;
ExternalCheck[] externalChecks;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {CommonTypes} from "src/common/CommonTypes.sol";
/// @notice Hashing of the common types, used for EIP712 signature verification.
abstract contract CommonTypesHashing is CommonTypes {
// keccak256("ExternalCheck(address contractAddress,bytes4 selector,bytes value,bool required)")
bytes32 private constant EXTERNAL_CHECK_TYPE_HASH = 0x8d4afe924d276922e1a624d4cc4d5b316cb369a5d290db2fae6417ec282d01f8;
// keccak256("Checks(uint256 uses,uint256 expiration,uint256 effective,bytes32 salt,uint256 contractSignatureIndex,uint256 signerSignatureIndex,bytes32 allowedRoot,ExternalCheck[] externalChecks)ExternalCheck(address contractAddress,bytes4 selector,bytes value,bool required)")
bytes32 private constant CHECKS_TYPE_HASH = 0xcae85973b802c2104c84d94b18a0a8a13a0576322547fe2fab563e83849ce641;
function _hashExternalChecks(ExternalCheck[] calldata _externalChecks) private pure returns (bytes32) {
bytes32[] memory hashes = new bytes32[](_externalChecks.length);
for (uint256 i = 0; i < hashes.length; i++) {
ExternalCheck calldata externalCheck = _externalChecks[i];
hashes[i] = keccak256(
abi.encode(
EXTERNAL_CHECK_TYPE_HASH,
externalCheck.contractAddress,
externalCheck.selector,
keccak256(externalCheck.value),
externalCheck.required
)
);
}
return keccak256(abi.encodePacked(hashes));
}
function _hashChecks(Checks calldata _checks) internal pure returns (bytes32) {
return keccak256(
abi.encode(
CHECKS_TYPE_HASH,
_checks.uses,
_checks.expiration,
_checks.effective,
_checks.salt,
_checks.contractSignatureIndex,
_checks.signerSignatureIndex,
_checks.allowedRoot,
_hashExternalChecks(_checks.externalChecks)
)
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {CommonTypes} from "src/common/CommonTypes.sol";
/// @notice Types used by the Coupons.
abstract contract CouponTypes is CommonTypes {
/// @notice Schema for the Coupon type.
/// @param signature Signature of the coupon.
/// @param checks Values to be verified before applying the coupon.
/// @param couponAddress Address of the Coupon contract to be used.
/// @param data Data to be used by the Coupon contract.
/// @param callerData Data sent by the caller to be used by the Coupon contract.
struct Coupon {
bytes signature;
Checks checks;
address couponAddress;
bytes data;
bytes callerData;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {EIP712} from "src/common/EIP712.sol";
import {IComposable} from "src/marketplace/interfaces/IComposable.sol";
import {MarketplaceWithCouponManager} from "src/marketplace/MarketplaceWithCouponManager.sol";
import {DecentralandMarketplaceEthereumAssetTypes} from "src/marketplace/DecentralandMarketplaceEthereumAssetTypes.sol";
import {FeeCollector} from "src/marketplace/FeeCollector.sol";
import {IAggregator} from "src/marketplace/interfaces/IAggregator.sol";
import {AggregatorHelper} from "src/marketplace/AggregatorHelper.sol";
/// @notice Decentraland Marketplace contract for the Ethereum network assets. MANA, LAND, Estates, Names, etc.
contract DecentralandMarketplaceEthereum is
DecentralandMarketplaceEthereumAssetTypes,
MarketplaceWithCouponManager,
FeeCollector,
AggregatorHelper
{
/// @notice The address of the MANA ERC20 contract.
/// @dev This will be used when transferring USD pegged MANA by enforcing this address as the Asset's contract address.
address public immutable manaAddress;
/// @notice The MANA/ETH Chainlink aggregator.
/// @dev Used to obtain the rate of MANA expressed in ETH.
/// Used along the ethUsdAggregator to calculate the MANA/USD rate for determining the MANA amount of USD pegged MANA assets.
IAggregator public manaEthAggregator;
/// @notice Maximum time (in seconds) since the MANA/ETH aggregator result was last updated before it is considered outdated.
uint256 public manaEthAggregatorTolerance;
/// @notice The ETH/USD Chainlink aggregator.
/// @dev Used to obtain the rate of ETH expressed in USD.
IAggregator public ethUsdAggregator;
/// @notice Maximum time (in seconds) since the ETH/USD aggregator result was last updated before it is considered outdated.
uint256 public ethUsdAggregatorTolerance;
event ManaEthAggregatorUpdated(address indexed _aggregator, uint256 _tolerance);
event EthUsdAggregatorUpdated(address indexed _aggregator, uint256 _tolerance);
error InvalidFingerprint();
/// @param _owner The owner of the contract.
/// @param _couponManager The address of the coupon manager contract.
/// @param _feeCollector The address that will receive erc20 fees.
/// @param _feeRate The rate of the fee. 25_000 is 2.5%
/// @param _manaAddress The address of the MANA ERC20 contract.
/// @param _manaEthAggregator The address of the MANA/ETH price aggregator.
/// @param _manaEthAggregatorTolerance The tolerance (in seconds) that indicates if the result provided by the aggregator is old.
/// @param _ethUsdAggregator The address of the ETH/USD price aggregator.
/// @param _ethUsdAggregatorTolerance The tolerance (in seconds) that indicates if the result provided by the aggregator is old.
constructor(
address _owner,
address _couponManager,
address _feeCollector,
uint256 _feeRate,
address _manaAddress,
address _manaEthAggregator,
uint256 _manaEthAggregatorTolerance,
address _ethUsdAggregator,
uint256 _ethUsdAggregatorTolerance
)
FeeCollector(_feeCollector, _feeRate)
EIP712("DecentralandMarketplaceEthereum", "1.0.0")
Ownable(_owner)
MarketplaceWithCouponManager(_couponManager)
{
manaAddress = _manaAddress;
_updateManaEthAggregator(_manaEthAggregator, _manaEthAggregatorTolerance);
_updateEthUsdAggregator(_ethUsdAggregator, _ethUsdAggregatorTolerance);
}
/// @notice Updates the fee collector address.
/// @param _feeCollector The new fee collector address.
function updateFeeCollector(address _feeCollector) external onlyOwner {
_updateFeeCollector(_msgSender(), _feeCollector);
}
/// @notice Updates the fee rate.
/// @param _feeRate The new fee rate.
function updateFeeRate(uint256 _feeRate) external onlyOwner {
_updateFeeRate(_msgSender(), _feeRate);
}
/// @notice Updates the MANA/ETH price aggregator and tolerance.
/// @param _aggregator The new MANA/ETH price aggregator.
/// @param _tolerance The new tolerance that indicates if the result provided by the aggregator is old.
function updateManaEthAggregator(address _aggregator, uint256 _tolerance) external onlyOwner {
_updateManaEthAggregator(_aggregator, _tolerance);
}
/// @notice Updates the ETH/USD price aggregator and tolerance.
/// @param _aggregator The new ETH/USD price aggregator.
/// @param _tolerance The new tolerance that indicates if the result provided by the aggregator is old.
function updateEthUsdAggregator(address _aggregator, uint256 _tolerance) external onlyOwner {
_updateEthUsdAggregator(_aggregator, _tolerance);
}
/// @dev Overridden Marketplace function to modify the trade before accepting it.
function _modifyTrade(Trade memory _trade) internal pure override {
/// This marketplace contract does not require to make any modifications to the Trade, so it remains empty.
}
/// @dev Overridden Marketplace function to transfer assets.
/// Handles the transfer of ERC20 and ERC721 assets.
function _transferAsset(Asset memory _asset, address _from, address, address) internal override {
uint256 assetType = _asset.assetType;
if (assetType == ASSET_TYPE_ERC20) {
_transferERC20(_asset, _from);
} else if (assetType == ASSET_TYPE_USD_PEGGED_MANA) {
_transferUsdPeggedMana(_asset, _from);
} else if (assetType == ASSET_TYPE_ERC721) {
_transferERC721(_asset, _from);
} else {
revert UnsupportedAssetType(assetType);
}
}
/// @dev Transfers ERC20 assets to the beneficiary.
/// A part of the value is taken as a fee and transferred to the fee collector.
function _transferERC20(Asset memory _asset, address _from) private {
uint256 originalValue = _asset.value;
uint256 fee = (originalValue * feeRate) / 1_000_000;
IERC20 erc20 = IERC20(_asset.contractAddress);
SafeERC20.safeTransferFrom(erc20, _from, _asset.beneficiary, originalValue - fee);
SafeERC20.safeTransferFrom(erc20, _from, feeCollector, fee);
}
/// @dev Transfers MANA to the beneficiary depending to the provided value in USD defined in the asset.
function _transferUsdPeggedMana(Asset memory _asset, address _from) private {
// Obtains the price of MANA in ETH.
int256 manaEthRate = _getRateFromAggregator(manaEthAggregator, manaEthAggregatorTolerance);
// Obtains the price of ETH in USD.
int256 ethUsdRate = _getRateFromAggregator(ethUsdAggregator, ethUsdAggregatorTolerance);
// With the obtained rates, we can calculate the price of MANA in USD.
int256 manaUsdRate = (manaEthRate * ethUsdRate) / 1e18;
// Updates the asset with the new values.
_updateAssetWithConvertedMANAPrice(_asset, manaAddress, manaUsdRate);
// With the updated asset, we can perform a normal ERC20 transfer.
_transferERC20(_asset, _from);
}
/// @dev Transfers ERC721 assets to the beneficiary.
/// Takes into account Composable ERC721 contracts like Estates.
function _transferERC721(Asset memory _asset, address _from) private {
IComposable erc721 = IComposable(_asset.contractAddress);
if (erc721.supportsInterface(erc721.verifyFingerprint.selector)) {
// Uses the extra data provided in the asset as the fingerprint to be verified.
if (!erc721.verifyFingerprint(_asset.value, _asset.extra)) {
revert InvalidFingerprint();
}
}
erc721.safeTransferFrom(_from, _asset.beneficiary, _asset.value);
}
/// @dev Updates the MANA/ETH price aggregator and tolerance.
function _updateManaEthAggregator(address _aggregator, uint256 _tolerance) private {
manaEthAggregator = IAggregator(_aggregator);
manaEthAggregatorTolerance = _tolerance;
emit ManaEthAggregatorUpdated(_aggregator, _tolerance);
}
/// @dev Updates the ETH/USD price aggregator and tolerance.
function _updateEthUsdAggregator(address _aggregator, uint256 _tolerance) private {
ethUsdAggregator = IAggregator(_aggregator);
ethUsdAggregatorTolerance = _tolerance;
emit EthUsdAggregatorUpdated(_aggregator, _tolerance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
/// @notice Asset types for the Decentraland Marketplace on Ethereum.
abstract contract DecentralandMarketplaceEthereumAssetTypes {
uint256 public constant ASSET_TYPE_ERC20 = 1;
uint256 public constant ASSET_TYPE_USD_PEGGED_MANA = 2;
uint256 public constant ASSET_TYPE_ERC721 = 3;
error UnsupportedAssetType(uint256 _assetType);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)
pragma solidity 0.8.20;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {ShortStrings, ShortString} from "@openzeppelin/contracts/utils/ShortStrings.sol";
/**
* @dev Modified implementation of OpenZeppelin's EIP712 to address specific requirements.
*
* The original implementation can be found at:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/dbb6104ce834628e473d2173bbc9d47f81a9eec3/contracts/utils/cryptography/EIP712.sol
*
* Changes from the OZ implementation include:
* 1. The TYPE_HASH no longer includes the chain ID. This modification allows users to sign messages for a different
* blockchain than the one where the contract is deployed. To prevent replay attacks, the target chain ID is
* specified in the `salt` parameter. This approach enhances user experience by eliminating the need for users
* to switch chains just to sign messages.
* 2. Removed the IERC5267 interface and the associated eip712Domain function. The reason for this removal is that
* the EIP712 domain structure in these contracts does not conform to the IERC5267 standard.
*
* All comments found underneath are from the original implementation.
*
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable
*/
abstract contract EIP712 {
using ShortStrings for *;
/// keccak256("EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)")
bytes32 private constant TYPE_HASH = 0x36c25de3e541d5d970f66e4210d728721220fff5c077cc6cd008b3a0c62adab7;
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
string private _nameFallback;
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, address(this), block.chainid));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: By default this function reads _name which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Name() internal view returns (string memory) {
return _name.toStringWithFallback(_nameFallback);
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: By default this function reads _version which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Version() internal view returns (string memory) {
return _version.toStringWithFallback(_versionFallback);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
/// @notice Contract that abstracts the storage of the fee collector and fee rate used by Marketplace contracts.
abstract contract FeeCollector {
/// @notice The address that will receive the fees.
address public feeCollector;
/// @notice The rate at which the fees will be charged. 25_000 is 2.5%
uint256 public feeRate;
event FeeCollectorUpdated(address indexed _caller, address indexed _feeCollector);
event FeeRateUpdated(address indexed _caller, uint256 _feeRate);
constructor(address _feeCollector, uint256 _feeRate) {
_updateFeeCollector(msg.sender, _feeCollector);
_updateFeeRate(msg.sender, _feeRate);
}
/// @dev Updates the fee collector address.
/// @param _caller The address of the user updating the collector.
/// @param _feeCollector The new address of the fee collector.
function _updateFeeCollector(address _caller, address _feeCollector) internal {
feeCollector = _feeCollector;
emit FeeCollectorUpdated(_caller, _feeCollector);
}
/// @dev Updates the fee rate.
/// @param _caller The address of the user updating the rate.
/// @param _feeRate The new fee rate.
function _updateFeeRate(address _caller, uint256 _feeRate) internal {
feeRate = _feeRate;
emit FeeRateUpdated(_caller, _feeRate);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
/// @notice Interface for Chainlink Aggregator contracts containing the methods used by the Marketplace contracts to obtain a rate.
interface IAggregator {
/// @notice Returns the number of decimals used by the Aggregator.
/// For example, MANA / ETH returns 18 decimals while ETH / USD returns 8 decimals.
/// Required to normalize the rate.
function decimals() external view returns (uint8);
/// @notice Function that returns the most recent rate.
/// The value currently used are "answer", containing the rate, and the "updatedAt" timestamp used to know if the value is not too old.
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {IERC721} from "@openzeppelin/contracts/interfaces/IERC721.sol";
/// @notice Interface for ERC721 Composable contracts.
interface IComposable is IERC721 {
function verifyFingerprint(uint256 _estateId, bytes memory _fingerprint) external view returns (bool);
function getFingerprint(uint256 _estateId) external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {CouponTypes} from "src/coupons/CouponTypes.sol";
import {MarketplaceTypes} from "src/marketplace/MarketplaceTypes.sol";
/// @notice Interface for the Coupon Manager contract.
interface ICouponManager {
function applyCoupon(MarketplaceTypes.Trade calldata _trade, CouponTypes.Coupon calldata _coupon) external returns (MarketplaceTypes.Trade memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1271.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../token/ERC721/IERC721.sol";
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Verifications} from "src/common/Verifications.sol";
import {MarketplaceTypesHashing} from "src/marketplace/MarketplaceTypesHashing.sol";
/// @notice Main Marketplace abstract contract that contains the logic to validate and accept Trades.
abstract contract Marketplace is Verifications, MarketplaceTypesHashing, Pausable, ReentrancyGuard {
/// @notice Trade ids that have been already used.
/// Trade ids are composed by hashing:
/// Salt + Caller + Received Assets (Contract Address + Value)
mapping(bytes32 => bool) public usedTradeIds;
/// @dev The event is emitted with the hashed signature so it can be identified off chain.
event Traded(address indexed _caller, bytes32 indexed _signature, Trade _trade);
error UsedTradeId();
/// @notice Pauses the contract so no new trades can be accepted.
function pause() external onlyOwner {
_pause();
}
/// @notice Unpauses the contract to resume normal operations.
function unpause() external onlyOwner {
_unpause();
}
/// @notice Revokes the signatures of all provided trades.
/// The caller must be the signer of those trades.
/// @param _trades The list of trade signatures to be canceled.
function cancelSignature(Trade[] calldata _trades) external {
address caller = _msgSender();
for (uint256 i = 0; i < _trades.length; i++) {
Trade calldata trade = _trades[i];
_verifyTradeSignature(trade, caller);
_cancelSignature(keccak256(trade.signature));
}
}
/// @notice Accept a list of Trades.
/// @param _trades The list of Trades to accept.
function accept(Trade[] calldata _trades) external whenNotPaused nonReentrant {
address caller = _msgSender();
for (uint256 i = 0; i < _trades.length; i++) {
_verifyTrade(_trades[i], caller);
_accept(_trades[i], caller);
}
}
/// @notice Returns the trade id for a given Trade.
/// @param _trade The Trade to get the id from.
/// @param _caller The address that called the contract.
///
/// @dev The trade id is composed of hashing the following values:
/// Salt + Caller + Received Assets (Contract Address + Value)
function getTradeId(Trade calldata _trade, address _caller) public pure returns (bytes32) {
bytes32 tradeId = keccak256(abi.encodePacked(_trade.checks.salt, _caller));
for (uint256 i = 0; i < _trade.received.length; i++) {
Asset calldata asset = _trade.received[i];
tradeId = keccak256(abi.encodePacked(tradeId, asset.contractAddress, asset.value));
}
return tradeId;
}
/// @dev Accepts a Trade.
/// This function is internal to allow child contracts to use it in their own accept function.
/// Does not perform any checks, only transfers the assets and emits the Traded event.
function _accept(Trade memory _trade, address _caller) internal {
_modifyTrade(_trade);
bytes32 hashedSignature = keccak256(_trade.signature);
address signer = _trade.signer;
_transferAssets(_trade.sent, signer, _caller, signer, _caller);
_transferAssets(_trade.received, _caller, signer, signer, _caller);
emit Traded(_caller, hashedSignature, _trade);
}
/// @dev Verifies that the Trade passes all checks and the signature is valid.
function _verifyTrade(Trade calldata _trade, address _caller) internal {
bytes32 hashedSignature = keccak256(_trade.signature);
address signer = _trade.signer;
bytes32 tradeId = getTradeId(_trade, _caller);
uint256 currentSignatureUses = signatureUses[hashedSignature];
if (usedTradeIds[tradeId]) {
revert UsedTradeId();
}
_verifyChecks(_trade.checks, hashedSignature, currentSignatureUses, signer, _caller);
_verifyTradeSignature(_trade, signer);
if (currentSignatureUses + 1 == _trade.checks.uses) {
usedTradeIds[tradeId] = true;
}
signatureUses[hashedSignature]++;
}
/// @dev Verifies that the Trade signature is valid.
function _verifyTradeSignature(Trade calldata _trade, address _signer) private view {
_verifySignature(_hashTrade(_trade), _trade.signature, _signer);
}
/// @dev Transfers all the provided assets using the overridden _transferAsset function.
/// Updates all the asset beneficiaries to the provided _to address in case the original beneficiary is the 0 address.
function _transferAssets(Asset[] memory _assets, address _from, address _to, address _signer, address _caller) private {
for (uint256 i = 0; i < _assets.length; i++) {
Asset memory asset = _assets[i];
if (asset.beneficiary == address(0)) {
asset.beneficiary = _to;
}
_transferAsset(asset, _from, _signer, _caller);
}
}
/// @dev Allows the child contract to update the Trade before accepting it.
function _modifyTrade(Trade memory _trade) internal view virtual;
/// @dev Allows the child contract to handle the transfer of assets.
function _transferAsset(Asset memory _asset, address _from, address _signer, address _caller) internal virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {CommonTypes} from "src/common/CommonTypes.sol";
/// @notice Types used by the Marketplace.
abstract contract MarketplaceTypes is CommonTypes {
/// @notice Schema for the Asset type.
/// This represents any kind of asset that will be traded.
/// @param assetType Type of the asset. Used to know how to handle it.
/// @param contractAddress Address of the contract of the asset.
/// @param value Value of the asset. The amount for ERC20s, the ID for ERC721s, etc.
/// @param beneficiary Address that will receive the asset. If empty, depending if the asset is sent or received, the beneficiary will be the signer or the caller.
/// In the case of sent assets, the beneficiary is not validated in the signature. This is to allow the caller to determine which address will receive the asset.
/// @param extra Extra data that can be used to store additional information.
struct Asset {
uint256 assetType;
address contractAddress;
uint256 value;
address beneficiary;
bytes extra;
}
/// @notice Schema for the Trade type.
/// This represents a signed Trade that indicates the terms of the Trade, as well as the assets involved.
/// @param signer Address of the signer of the Trade.
/// @param signature Signature of the Trade.
/// @param checks Checks to be performed before executing the Trade.
/// @param sent Assets that will be sent to the caller in the Trade.
/// @param received Assets that will be received by the signer in the Trade.
struct Trade {
address signer;
bytes signature;
Checks checks;
Asset[] sent;
Asset[] received;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {CommonTypesHashing} from "src/common/CommonTypesHashing.sol";
import {MarketplaceTypes} from "src/marketplace/MarketplaceTypes.sol";
/// @notice Hashing functions for the Marketplace types. Used for EIP712 signatures.
abstract contract MarketplaceTypesHashing is MarketplaceTypes, CommonTypesHashing {
// keccak256("AssetWithoutBeneficiary(uint256 assetType,address contractAddress,uint256 value,bytes extra)")
bytes32 private constant ASSET_WO_BENEFICIARY_TYPE_HASH = 0x7be57332caf51c5f0f0fa0e7c362534d22d81c0bee1ffac9b573acd336e032bd;
// keccak256("Asset(uint256 assetType,address contractAddress,uint256 value,bytes extra,address beneficiary)")
bytes32 private constant ASSET_TYPE_HASH = 0xe5f9e1ebc316d1bde562c77f47da7dc2cccb903eb04f9b82e29212b96f9e57e1;
// keccak256("Trade(Checks checks,AssetWithoutBeneficiary[] sent,Asset[] received)Asset(uint256 assetType,address contractAddress,uint256 value,bytes extra,address beneficiary)AssetWithoutBeneficiary(uint256 assetType,address contractAddress,uint256 value,bytes extra)Checks(uint256 uses,uint256 expiration,uint256 effective,bytes32 salt,uint256 contractSignatureIndex,uint256 signerSignatureIndex,bytes32 allowedRoot,ExternalCheck[] externalChecks)ExternalCheck(address contractAddress,bytes4 selector,bytes value,bool required)")
bytes32 private constant TRADE_TYPE_HASH = 0x1bb41340c6ec0467bb14b59212e1189437e71660f2ef919bda2be2f2065dfe6c;
function _hashAssetsWithoutBeneficiary(Asset[] calldata _assets) private pure returns (bytes32) {
bytes32[] memory hashes = new bytes32[](_assets.length);
for (uint256 i = 0; i < hashes.length; i++) {
Asset calldata asset = _assets[i];
hashes[i] = keccak256(
abi.encode(
ASSET_WO_BENEFICIARY_TYPE_HASH,
asset.assetType,
asset.contractAddress,
asset.value,
keccak256(asset.extra)
)
);
}
return keccak256(abi.encodePacked(hashes));
}
function _hashAssets(Asset[] calldata _assets) private pure returns (bytes32) {
bytes32[] memory hashes = new bytes32[](_assets.length);
for (uint256 i = 0; i < hashes.length; i++) {
Asset calldata asset = _assets[i];
hashes[i] = keccak256(
abi.encode(
ASSET_TYPE_HASH,
asset.assetType,
asset.contractAddress,
asset.value,
keccak256(asset.extra),
asset.beneficiary
)
);
}
return keccak256(abi.encodePacked(hashes));
}
function _hashTrade(Trade calldata _trade) internal pure returns (bytes32) {
return keccak256(
abi.encode(
TRADE_TYPE_HASH,
_hashChecks(_trade.checks),
_hashAssetsWithoutBeneficiary(_trade.sent),
_hashAssets(_trade.received)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {Marketplace} from "src/marketplace/Marketplace.sol";
import {ICouponManager} from "src/coupons/interfaces/ICouponManager.sol";
import {CouponTypes} from "src/coupons/CouponTypes.sol";
/// @notice Marketplace contract that also allows the use of coupons.
/// Coupons are a way to modify Trades before they are executed, like Discounts.
abstract contract MarketplaceWithCouponManager is Marketplace, CouponTypes {
/// @notice The address of the CouponManager contract.
ICouponManager public couponManager;
event CouponManagerUpdated(address indexed _caller, address indexed _couponManager);
constructor(address _couponManager) {
_updateCouponManager(_couponManager);
}
/// @notice Accepts a list of Trades with the given Coupons.
/// @param _trades The list of Trades to accept.
/// @param _coupons The list of Coupons to apply to the Trades.
function acceptWithCoupon(Trade[] calldata _trades, Coupon[] calldata _coupons) external whenNotPaused nonReentrant {
address caller = _msgSender();
for (uint256 i = 0; i < _trades.length; i++) {
// It is important to verify the Trade before applying the coupons to avoid issues with the signature.
_verifyTrade(_trades[i], caller);
// Modify the Trade with the coupon and accept it normally.
_accept(couponManager.applyCoupon(_trades[i], _coupons[i]), caller);
}
}
/// @notice Updates the CouponManager address.
/// @param _couponManager The new address of the CouponManager.
function updateCouponManager(address _couponManager) external onlyOwner {
_updateCouponManager(_couponManager);
}
function _updateCouponManager(address _couponManager) private {
couponManager = ICouponManager(_couponManager);
emit CouponManagerUpdated(_msgSender(), _couponManager);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.20;
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*/
library MerkleProof {
/**
*@dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Calldata version of {verify}
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Calldata version of {processProof}
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Calldata version of {multiProofVerify}
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
if (leavesLen + proofLen != totalHashes + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Calldata version of {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
if (leavesLen + proofLen != totalHashes + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Sorts the pair (a, b) and hashes the result.
*/
function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../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 An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, 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);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @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.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @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);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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(token).code.length > 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
/// @solidity memory-safe-assembly
assembly {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
* {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.20;
import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
* signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
* Argent and Safe Wallet (previously Gnosis Safe).
*/
library SignatureChecker {
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error, ) = ECDSA.tryRecover(hash, signature);
return
(error == ECDSA.RecoverError.NoError && recovered == signer) ||
isValidERC1271SignatureNow(signer, hash, signature);
}
/**
* @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
* against the signer smart contract using ERC1271.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidERC1271SignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(bool success, bytes memory result) = signer.staticcall(
abi.encodeCall(IERC1271.isValidSignature, (hash, signature))
);
return (success &&
result.length >= 32 &&
abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {EIP712} from "src/common/EIP712.sol";
/// @dev Adds some functions to manage signatures.
abstract contract Signatures is Ownable, EIP712 {
/// @notice Value of the current contract signature index.
/// The owner of the contract can update this value to revoke signatures created with another value.
uint256 public contractSignatureIndex;
/// @notice Value of the current signer signature index.
/// Signers can update this value to revoke signatures created with another value.
mapping(address => uint256) public signerSignatureIndex;
/// @notice Mapping of cancelled signatures.
/// Signers can invalidate any particular signature by adding it to this mapping.
mapping(bytes32 => bool) public cancelledSignatures;
/// @notice Mapping of signature uses.
/// Tracks how many times a signature has been used.
/// Useful in case the signer wants to determine how many times a signature can be used.
mapping(bytes32 => uint256) public signatureUses;
event ContractSignatureIndexIncreased(address indexed _caller, uint256 indexed _newValue);
event SignerSignatureIndexIncreased(address indexed _caller, uint256 indexed _newValue);
event SignatureCancelled(address indexed _caller, bytes32 indexed _signature);
error InvalidSignature();
/// @notice Allows the owner of the contract to increase the contract signature index.
/// Revokes all signatures created with a previous index.
function increaseContractSignatureIndex() external onlyOwner {
uint256 newIndex = ++contractSignatureIndex;
emit ContractSignatureIndexIncreased(_msgSender(), newIndex);
}
/// @notice Allows the signer to increase their signature index.
/// Revokes all signatures created by the signer with a previous index.
function increaseSignerSignatureIndex() external {
address caller = _msgSender();
uint256 newIndex = ++signerSignatureIndex[caller];
emit SignerSignatureIndexIncreased(caller, newIndex);
}
/// @dev Useful to cancel a signature so it cannot be used anymore.
/// The implementation should call this function after validating that the caller is the creator of the signature.
/// @param _hashedSignature The hash of the signature to cancel.
function _cancelSignature(bytes32 _hashedSignature) internal {
cancelledSignatures[_hashedSignature] = true;
emit SignatureCancelled(_msgSender(), _hashedSignature);
}
/// @dev Verifies that a signature has been signed by a particular signer.
/// @param _typeHash The type hash.
/// @param _signature The signature.
/// @param _signer The signer who is supposed to have signed the signature.
function _verifySignature(bytes32 _typeHash, bytes calldata _signature, address _signer) internal view {
if (!SignatureChecker.isValidSignatureNow(_signer, _hashTypedDataV4(_typeHash), _signature)) {
revert InvalidSignature();
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {Signatures} from "src/common/Signatures.sol";
import {CommonTypes} from "src/common/CommonTypes.sol";
/// @notice Contract that provides a function to verify Checks.
abstract contract Verifications is Signatures, CommonTypes {
/// bytes4(keccak256("balanceOf(address)"))
bytes4 private constant BALANCE_OF_SELECTOR = 0x70a08231;
/// bytes4(keccak256("ownerOf(uint256)"))
bytes4 private constant OWNER_OF_SELECTOR = 0x6352211e;
error UsingCancelledSignature();
error SignatureOveruse();
error NotEffective();
error InvalidContractSignatureIndex();
error InvalidSignerSignatureIndex();
error Expired();
error NotAllowed();
error ExternalChecksFailed();
/// @dev Verifies that the Check values are correct and that the signature has not been canceled or overused.
/// @param _checks The Checks to verify.
/// @param _hashedSignature The hash of the signature.
/// @param _currentSignatureUses The number of times the signature has been used.
/// @param _signer The address that created the signature.
/// @param _caller The address that sent the transaction.
function _verifyChecks(Checks calldata _checks, bytes32 _hashedSignature, uint256 _currentSignatureUses, address _signer, address _caller)
internal
view
{
if (cancelledSignatures[_hashedSignature]) {
revert UsingCancelledSignature();
}
if (_currentSignatureUses >= _checks.uses) {
revert SignatureOveruse();
}
if (_checks.effective > block.timestamp) {
revert NotEffective();
}
if (contractSignatureIndex != _checks.contractSignatureIndex) {
revert InvalidContractSignatureIndex();
}
if (signerSignatureIndex[_signer] != _checks.signerSignatureIndex) {
revert InvalidSignerSignatureIndex();
}
if (_checks.expiration < block.timestamp) {
revert Expired();
}
if (_checks.allowedRoot != 0) {
_verifyAllowed(_checks.allowedRoot, _checks.allowedProof, _caller);
}
if (_checks.externalChecks.length > 0) {
_verifyExternalChecks(_checks.externalChecks, _caller);
}
}
/// @dev Verifies that the provided caller is allowed.
/// @param _allowedRoot The Merkle Root of the allowed addresses.
/// @param _allowedProof The Merkle Proof that validates that the caller is allowed.
/// @param _caller The address that sent the transaction.
function _verifyAllowed(bytes32 _allowedRoot, bytes32[] calldata _allowedProof, address _caller) private pure {
if (!MerkleProof.verify(_allowedProof, _allowedRoot, keccak256(bytes.concat(keccak256(abi.encode(address(_caller))))))) {
revert NotAllowed();
}
}
/// @dev Verifies that the external checks are met.
/// @param _externalChecks The external checks to verify.
/// @param _caller The address that sent the transaction.
///
/// External checks can be defined as required or optional. If any required check fails, the function will revert.
/// Regarding optional checks, it only makes sense when there are more than one. If there is only one optional check, even if there are other required checks, it will be treated as required.
/// For example:
/// - 1 optional check === 1 required check.
/// - 1 required check + 1 optional check === 2 required checks.
///
/// If the selector is `balanceOf`, it will be checked that the balance is greater than or equal to the `value`.
/// If the selector is `ownerOf`, it will be checked that the owner of `value` is the caller.
/// Otherwise, the function will call the selector with the caller and value, and expect it to return true.
function _verifyExternalChecks(ExternalCheck[] calldata _externalChecks, address _caller) private view {
bool hasOptionalChecks = false;
bool hasPassingOptionalCheck = false;
for (uint256 i = 0; i < _externalChecks.length; i++) {
ExternalCheck calldata externalCheck = _externalChecks[i];
bool isRequiredCheck = externalCheck.required;
if (!isRequiredCheck && hasPassingOptionalCheck) {
// If there is already a passing optional check, there is no need to evaluate the others.
continue;
}
bytes4 selector = externalCheck.selector;
bytes memory functionData;
if (selector == BALANCE_OF_SELECTOR) {
// balanceOf(address _user)
functionData = abi.encodeWithSelector(selector, _caller);
} else if (selector == OWNER_OF_SELECTOR) {
// ownerOf(uint256 _tokenId)
functionData = abi.encodeWithSelector(selector, abi.decode(externalCheck.value, (uint256)));
} else {
// custom(address _user, bytes _value)
functionData = abi.encodeWithSelector(selector, _caller, externalCheck.value);
}
// Call the external contract to check the condition.
(bool success, bytes memory data) = externalCheck.contractAddress.staticcall(functionData);
if (!success) {
// Do nothing here, an unsuccessful call will be treated as a failed check later.
} else if (selector == BALANCE_OF_SELECTOR) {
// Check that the returned balance is >= the provided value.
success = abi.decode(data, (uint256)) >= abi.decode(externalCheck.value, (uint256));
} else if (selector == OWNER_OF_SELECTOR) {
// Check that the owner of the nft is the caller.
success = abi.decode(data, (address)) == _caller;
} else {
// Check that the custom function returned true.
success = abi.decode(data, (bool));
}
// There is no need to proceed if a required check fails.
if (!success && isRequiredCheck) {
revert ExternalChecksFailed();
}
if (!isRequiredCheck) {
// Track that there is at least one optional check.
hasOptionalChecks = true;
if (success) {
// Track that there is at least one passing optional check.
hasPassingOptionalCheck = true;
}
}
}
// Fails if there were optional checks and none of them passed.
if (hasOptionalChecks && !hasPassingOptionalCheck) {
revert ExternalChecksFailed();
}
}
}
{
"compilationTarget": {
"src/marketplace/DecentralandMarketplaceEthereum.sol": "DecentralandMarketplaceEthereum"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
":ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}
[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_couponManager","type":"address"},{"internalType":"address","name":"_feeCollector","type":"address"},{"internalType":"uint256","name":"_feeRate","type":"uint256"},{"internalType":"address","name":"_manaAddress","type":"address"},{"internalType":"address","name":"_manaEthAggregator","type":"address"},{"internalType":"uint256","name":"_manaEthAggregatorTolerance","type":"uint256"},{"internalType":"address","name":"_ethUsdAggregator","type":"address"},{"internalType":"uint256","name":"_ethUsdAggregatorTolerance","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"AggregatorAnswerIsNegative","type":"error"},{"inputs":[],"name":"AggregatorAnswerIsStale","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"Expired","type":"error"},{"inputs":[],"name":"ExternalChecksFailed","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"InvalidContractSignatureIndex","type":"error"},{"inputs":[],"name":"InvalidFingerprint","type":"error"},{"inputs":[],"name":"InvalidSignature","type":"error"},{"inputs":[],"name":"InvalidSignerSignatureIndex","type":"error"},{"inputs":[],"name":"NotAllowed","type":"error"},{"inputs":[],"name":"NotEffective","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"SignatureOveruse","type":"error"},{"inputs":[{"internalType":"string","name":"str","type":"string"}],"name":"StringTooLong","type":"error"},{"inputs":[{"internalType":"uint256","name":"_assetType","type":"uint256"}],"name":"UnsupportedAssetType","type":"error"},{"inputs":[],"name":"UsedTradeId","type":"error"},{"inputs":[],"name":"UsingCancelledSignature","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_caller","type":"address"},{"indexed":true,"internalType":"uint256","name":"_newValue","type":"uint256"}],"name":"ContractSignatureIndexIncreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_caller","type":"address"},{"indexed":true,"internalType":"address","name":"_couponManager","type":"address"}],"name":"CouponManagerUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_aggregator","type":"address"},{"indexed":false,"internalType":"uint256","name":"_tolerance","type":"uint256"}],"name":"EthUsdAggregatorUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_caller","type":"address"},{"indexed":true,"internalType":"address","name":"_feeCollector","type":"address"}],"name":"FeeCollectorUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_caller","type":"address"},{"indexed":false,"internalType":"uint256","name":"_feeRate","type":"uint256"}],"name":"FeeRateUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_aggregator","type":"address"},{"indexed":false,"internalType":"uint256","name":"_tolerance","type":"uint256"}],"name":"ManaEthAggregatorUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_caller","type":"address"},{"indexed":true,"internalType":"bytes32","name":"_signature","type":"bytes32"}],"name":"SignatureCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_caller","type":"address"},{"indexed":true,"internalType":"uint256","name":"_newValue","type":"uint256"}],"name":"SignerSignatureIndexIncreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_caller","type":"address"},{"indexed":true,"internalType":"bytes32","name":"_signature","type":"bytes32"},{"components":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"},{"components":[{"internalType":"uint256","name":"uses","type":"uint256"},{"internalType":"uint256","name":"expiration","type":"uint256"},{"internalType":"uint256","name":"effective","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256","name":"contractSignatureIndex","type":"uint256"},{"internalType":"uint256","name":"signerSignatureIndex","type":"uint256"},{"internalType":"bytes32","name":"allowedRoot","type":"bytes32"},{"internalType":"bytes32[]","name":"allowedProof","type":"bytes32[]"},{"components":[{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"bytes4","name":"selector","type":"bytes4"},{"internalType":"bytes","name":"value","type":"bytes"},{"internalType":"bool","name":"required","type":"bool"}],"internalType":"struct CommonTypes.ExternalCheck[]","name":"externalChecks","type":"tuple[]"}],"internalType":"struct CommonTypes.Checks","name":"checks","type":"tuple"},{"components":[{"internalType":"uint256","name":"assetType","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bytes","name":"extra","type":"bytes"}],"internalType":"struct MarketplaceTypes.Asset[]","name":"sent","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"assetType","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bytes","name":"extra","type":"bytes"}],"internalType":"struct MarketplaceTypes.Asset[]","name":"received","type":"tuple[]"}],"indexed":false,"internalType":"struct MarketplaceTypes.Trade","name":"_trade","type":"tuple"}],"name":"Traded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"ASSET_TYPE_ERC20","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ASSET_TYPE_ERC721","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ASSET_TYPE_USD_PEGGED_MANA","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"},{"components":[{"internalType":"uint256","name":"uses","type":"uint256"},{"internalType":"uint256","name":"expiration","type":"uint256"},{"internalType":"uint256","name":"effective","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256","name":"contractSignatureIndex","type":"uint256"},{"internalType":"uint256","name":"signerSignatureIndex","type":"uint256"},{"internalType":"bytes32","name":"allowedRoot","type":"bytes32"},{"internalType":"bytes32[]","name":"allowedProof","type":"bytes32[]"},{"components":[{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"bytes4","name":"selector","type":"bytes4"},{"internalType":"bytes","name":"value","type":"bytes"},{"internalType":"bool","name":"required","type":"bool"}],"internalType":"struct CommonTypes.ExternalCheck[]","name":"externalChecks","type":"tuple[]"}],"internalType":"struct CommonTypes.Checks","name":"checks","type":"tuple"},{"components":[{"internalType":"uint256","name":"assetType","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bytes","name":"extra","type":"bytes"}],"internalType":"struct MarketplaceTypes.Asset[]","name":"sent","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"assetType","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bytes","name":"extra","type":"bytes"}],"internalType":"struct MarketplaceTypes.Asset[]","name":"received","type":"tuple[]"}],"internalType":"struct MarketplaceTypes.Trade[]","name":"_trades","type":"tuple[]"}],"name":"accept","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"},{"components":[{"internalType":"uint256","name":"uses","type":"uint256"},{"internalType":"uint256","name":"expiration","type":"uint256"},{"internalType":"uint256","name":"effective","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256","name":"contractSignatureIndex","type":"uint256"},{"internalType":"uint256","name":"signerSignatureIndex","type":"uint256"},{"internalType":"bytes32","name":"allowedRoot","type":"bytes32"},{"internalType":"bytes32[]","name":"allowedProof","type":"bytes32[]"},{"components":[{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"bytes4","name":"selector","type":"bytes4"},{"internalType":"bytes","name":"value","type":"bytes"},{"internalType":"bool","name":"required","type":"bool"}],"internalType":"struct CommonTypes.ExternalCheck[]","name":"externalChecks","type":"tuple[]"}],"internalType":"struct CommonTypes.Checks","name":"checks","type":"tuple"},{"components":[{"internalType":"uint256","name":"assetType","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bytes","name":"extra","type":"bytes"}],"internalType":"struct MarketplaceTypes.Asset[]","name":"sent","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"assetType","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bytes","name":"extra","type":"bytes"}],"internalType":"struct MarketplaceTypes.Asset[]","name":"received","type":"tuple[]"}],"internalType":"struct MarketplaceTypes.Trade[]","name":"_trades","type":"tuple[]"},{"components":[{"internalType":"bytes","name":"signature","type":"bytes"},{"components":[{"internalType":"uint256","name":"uses","type":"uint256"},{"internalType":"uint256","name":"expiration","type":"uint256"},{"internalType":"uint256","name":"effective","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256","name":"contractSignatureIndex","type":"uint256"},{"internalType":"uint256","name":"signerSignatureIndex","type":"uint256"},{"internalType":"bytes32","name":"allowedRoot","type":"bytes32"},{"internalType":"bytes32[]","name":"allowedProof","type":"bytes32[]"},{"components":[{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"bytes4","name":"selector","type":"bytes4"},{"internalType":"bytes","name":"value","type":"bytes"},{"internalType":"bool","name":"required","type":"bool"}],"internalType":"struct CommonTypes.ExternalCheck[]","name":"externalChecks","type":"tuple[]"}],"internalType":"struct CommonTypes.Checks","name":"checks","type":"tuple"},{"internalType":"address","name":"couponAddress","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"bytes","name":"callerData","type":"bytes"}],"internalType":"struct CouponTypes.Coupon[]","name":"_coupons","type":"tuple[]"}],"name":"acceptWithCoupon","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"},{"components":[{"internalType":"uint256","name":"uses","type":"uint256"},{"internalType":"uint256","name":"expiration","type":"uint256"},{"internalType":"uint256","name":"effective","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256","name":"contractSignatureIndex","type":"uint256"},{"internalType":"uint256","name":"signerSignatureIndex","type":"uint256"},{"internalType":"bytes32","name":"allowedRoot","type":"bytes32"},{"internalType":"bytes32[]","name":"allowedProof","type":"bytes32[]"},{"components":[{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"bytes4","name":"selector","type":"bytes4"},{"internalType":"bytes","name":"value","type":"bytes"},{"internalType":"bool","name":"required","type":"bool"}],"internalType":"struct CommonTypes.ExternalCheck[]","name":"externalChecks","type":"tuple[]"}],"internalType":"struct CommonTypes.Checks","name":"checks","type":"tuple"},{"components":[{"internalType":"uint256","name":"assetType","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bytes","name":"extra","type":"bytes"}],"internalType":"struct MarketplaceTypes.Asset[]","name":"sent","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"assetType","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bytes","name":"extra","type":"bytes"}],"internalType":"struct MarketplaceTypes.Asset[]","name":"received","type":"tuple[]"}],"internalType":"struct MarketplaceTypes.Trade[]","name":"_trades","type":"tuple[]"}],"name":"cancelSignature","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"cancelledSignatures","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"contractSignatureIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"couponManager","outputs":[{"internalType":"contract ICouponManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ethUsdAggregator","outputs":[{"internalType":"contract IAggregator","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ethUsdAggregatorTolerance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeCollector","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"},{"components":[{"internalType":"uint256","name":"uses","type":"uint256"},{"internalType":"uint256","name":"expiration","type":"uint256"},{"internalType":"uint256","name":"effective","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256","name":"contractSignatureIndex","type":"uint256"},{"internalType":"uint256","name":"signerSignatureIndex","type":"uint256"},{"internalType":"bytes32","name":"allowedRoot","type":"bytes32"},{"internalType":"bytes32[]","name":"allowedProof","type":"bytes32[]"},{"components":[{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"bytes4","name":"selector","type":"bytes4"},{"internalType":"bytes","name":"value","type":"bytes"},{"internalType":"bool","name":"required","type":"bool"}],"internalType":"struct CommonTypes.ExternalCheck[]","name":"externalChecks","type":"tuple[]"}],"internalType":"struct CommonTypes.Checks","name":"checks","type":"tuple"},{"components":[{"internalType":"uint256","name":"assetType","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bytes","name":"extra","type":"bytes"}],"internalType":"struct MarketplaceTypes.Asset[]","name":"sent","type":"tuple[]"},{"components":[{"internalType":"uint256","name":"assetType","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"bytes","name":"extra","type":"bytes"}],"internalType":"struct MarketplaceTypes.Asset[]","name":"received","type":"tuple[]"}],"internalType":"struct MarketplaceTypes.Trade","name":"_trade","type":"tuple"},{"internalType":"address","name":"_caller","type":"address"}],"name":"getTradeId","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"increaseContractSignatureIndex","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"increaseSignerSignatureIndex","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"manaAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"manaEthAggregator","outputs":[{"internalType":"contract IAggregator","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"manaEthAggregatorTolerance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"signatureUses","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"signerSignatureIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_couponManager","type":"address"}],"name":"updateCouponManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_aggregator","type":"address"},{"internalType":"uint256","name":"_tolerance","type":"uint256"}],"name":"updateEthUsdAggregator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_feeCollector","type":"address"}],"name":"updateFeeCollector","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_feeRate","type":"uint256"}],"name":"updateFeeRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_aggregator","type":"address"},{"internalType":"uint256","name":"_tolerance","type":"uint256"}],"name":"updateManaEthAggregator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"usedTradeIds","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]