Verified contractExactAGPL-3.0-only
GigaAggregator
Address0xdc077a4e3f46138dedac5d684882d33fcc927cf7
- Balance
0 ETH
- Transactions
86
- Compiler
solc 0.8.15
- Same code
Only this contract
Details
- Compiler
- solc 0.8.15+commit.e14f2714
- Language
- solidity
- Optimization
- Yes, 1,337 runs
- License
- AGPL-3.0-only
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 16,474,823
- Creation transaction
- 0xaa632e0c5d…5b5d18a2ff
45 files
- contracts/aggregator/GigaAggregator.solmain9.9 KB
- @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol3.15 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol6.63 KB
- @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol3.09 KB
- @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol3.38 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol2.78 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol2.26 KB
- @openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol4.59 KB
- @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol8.28 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.35 KB
- @openzeppelin/contracts/access/Ownable.sol2.62 KB
- @openzeppelin/contracts/interfaces/IERC1271.sol666 B
- @openzeppelin/contracts/security/ReentrancyGuard.sol2.66 KB
- @openzeppelin/contracts/token/ERC1155/IERC1155.sol4.07 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.77 KB
- @openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol2.25 KB
- @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol4.46 KB
- @openzeppelin/contracts/token/ERC721/IERC721.sol4.75 KB
- @openzeppelin/contracts/utils/Address.sol8.31 KB
- @openzeppelin/contracts/utils/Context.sol844 B
- @openzeppelin/contracts/utils/Strings.sol2.4 KB
- @openzeppelin/contracts/utils/cryptography/ECDSA.sol9.39 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol853 B
- contracts/access/PermitControl.sol7.15 KB
- contracts/aggregator/AggregatorTradeFinalizer.sol4.84 KB
- contracts/aggregator/lib/Configuration.sol5.19 KB
- contracts/aggregator/lib/EscapeHatch.sol4.53 KB
- contracts/marketplace/interfaces/IProxyRegistry.sol1.79 KB
- contracts/marketplace/libraries/NativeTransfer.sol958 B
- contracts/marketplace/proxy/TokenTransferProxy.sol1.85 KB
- contracts/test/looksrare/LooksRareExchange.sol25.23 KB
- contracts/test/looksrare/interfaces/ICurrencyManager.sol497 B
- contracts/test/looksrare/interfaces/IExecutionManager.sol498 B
- contracts/test/looksrare/interfaces/IExecutionStrategy.sol703 B
- contracts/test/looksrare/interfaces/ILooksRareExchange.sol605 B
- contracts/test/looksrare/interfaces/IRoyaltyFeeManager.sol273 B
- contracts/test/looksrare/interfaces/ITransferManagerNFT.sol276 B
- contracts/test/looksrare/interfaces/ITransferSelectorNFT.sol193 B
- contracts/test/looksrare/interfaces/IWETH.sol246 B
- contracts/test/looksrare/libraries/OrderTypes.sol2.8 KB
- contracts/test/looksrare/libraries/SignatureChecker.sol2.75 KB
- contracts/test/x2y2/IDelegate.sol928 B
- contracts/test/x2y2/IWETHUpgradable.sol314 B
- contracts/test/x2y2/MarketConsts.sol2.26 KB
- contracts/test/x2y2/X2Y2Exchange.sol20.25 KB
contracts/aggregator/GigaAggregator.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.15;
import {
ReentrancyGuard
} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {
Configuration,
EscapeHatch,
AggregatorTradeFinalizer,
IERC20,
SafeERC20
} from "./lib/Configuration.sol";
import {
TokenTransferProxy
} from "../marketplace/proxy/TokenTransferProxy.sol";
import {
NativeTransfer
} from "./../marketplace/libraries/NativeTransfer.sol";
/**
Thrown if an Ether payment to the aggregator does not match the provided
message value.
@param paymentAmount The payment amount to match with the message value.
@param messageValue The message value to match.
*/
error ExpectedValueDiffers (
uint256 paymentAmount,
uint256 messageValue
);
/// Thrown if purchases in the aggregator are paused.
error Paused ();
/**
@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
@title GigaMart Aggregator
@author Rostislav Khlebnikov <@catpic5buck>
@custom:contributor Tim Clancy <@_Enoch>
This contract implements a multi-market aggregator for GigaMart.
@custom:version 1.2
@custom:date Januart 24th, 2023.
*/
contract GigaAggregator is Configuration, ReentrancyGuard {
using SafeERC20 for IERC20;
using NativeTransfer for address;
/// A name used for this contract.
string public constant name = "GigaAggregator v1.2";
/// Track the slot for a supported exchange.
uint256 private constant _SUPPORTED_EXCHANGES_SLOT = 4;
/**
A convenience struct to contain information regarding total payment amounts
accross all orders.
@param asset The address of a payment token.
@param amount The amount of asset being paid.
*/
struct Payment {
address asset;
uint256 amount;
}
/// Store an immutable reference to a token transfer proxy.
TokenTransferProxy public immutable TOKEN_TRANSFER_PROXY;
/**
Construct a new GigaMart aggregator.
@param _exchanges An array of exchange addresses to mark as supported.
@param _tokens An array of payment tokens to approve to `_transferProxies`.
@param _transferProxies An array of addresses to set approval for on behalf
of this contract.
@param _tokenTransferProxy The address of a token transfer proxy.
@param _governance The address of a caller which has rights to manage
payment tokens.
@param _rescuer An address that can pause or unpause the contract and
rescue assets.
*/
constructor (
address[] memory _exchanges,
address[] memory _tokens,
address[] memory _transferProxies,
TokenTransferProxy _tokenTransferProxy,
address _governance,
address _rescuer
) Configuration(
_exchanges,
_tokens,
_transferProxies,
_governance,
_rescuer
) {
TOKEN_TRANSFER_PROXY = _tokenTransferProxy;
}
/// Add a payable receive function so that the aggregator can receive Ether.
receive () external payable { }
/// Return the magic value signifying the ability to receive ERC-721 items.
function onERC721Received (
address,
address,
uint256,
bytes memory
) public pure returns (bytes4) {
return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"));
}
/// Return the magic value signifying the ability to receive ERC-1155 items.
function onERC1155Received (
address,
address,
uint256,
uint256,
bytes memory
) public pure returns (bytes4) {
return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"));
}
/// Return the magic value signifying the ability to batch receive ERC-1155.
function onERC1155BatchReceived (
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public pure returns (bytes4) {
return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"));
}
/**
Reads balances of this contract on payment assets.
@param _payments An array containing information about token addresses and
the total token amounts needed to purchase all orders in the cart.
@param _balances An array for accumulating the balance of this contract for
each asset.
*/
function _readBalances (
Payment[] calldata _payments,
uint256[] memory _balances
) private view {
for (uint256 i; i < _payments.length; ) {
/*
Determine the balance of this aggregator contract in either Ether or
ERC-20 token, depending on the payment asset.
*/
_balances[i] = _payments[i].asset == address(0)
? address(this).balance - msg.value
: IERC20(_payments[i].asset).balanceOf(address(this));
unchecked {
++i;
}
}
}
/**
This function transfers ERC-20 tokens to this aggregator contract which
later will be used for executing purchases from cart. The function also
verifies native payment.
@param _payments An array containing information about token addresses and
the total token amounts needed to purchase all orders in the cart.
@custom:throws ExpectedValueDiffers if the message value does not match a
provided Ether payment amount.
*/
function _gatherPayments (
Payment[] calldata _payments
) private {
for (uint256 i; i < _payments.length; ) {
// Revert if there is a mismatched Ether balance.
bool native = _payments[i].asset == address(0);
if (native && _payments[i].amount != msg.value) {
revert ExpectedValueDiffers(_payments[i].amount, msg.value);
}
// Transfer ERC-20 tokens.
if (!native) {
TOKEN_TRANSFER_PROXY.transferERC20(
_payments[i].asset,
msg.sender,
address(this),
_payments[i].amount
);
}
unchecked {
++i;
}
}
}
/**
Parse the cart and call targeted exchanges.
@param _cart The cart to fulfill item purchase calls from.
*/
function _buy (
bytes calldata _cart
) private {
// An offset to the start of the cart full of calls.
uint256 offset = 0x64;
while (offset < _cart.length) {
assembly {
// Retrieve the length of this call.
let length := calldataload(add(offset, 0x20))
// Retrieve the exchange for fulfilling purchase of this call.
let exchange := calldataload(offset)
// Store the exchange and a mapping slot into memory.
mstore(0x00, exchange)
mstore(0x20, _SUPPORTED_EXCHANGES_SLOT)
/*
Hash the exchange and its storage slot, then load the resulting
address of the storage slot into memory. If the exchange is
supported, continue.
*/
let supported := sload(keccak256(0x00, 0x40))
if shr(0x80, supported) {
// Load the free memory pointer.
let ptr := mload(0x40)
// Copy the call into memory.
calldatacopy(ptr, add(offset, 0x60), length)
// Pop the result of the call from the stack, ignoring it.
let result :=
// Perform the call from the cart.
call(
gas(),
exchange,
calldataload(add(offset, 0x40)),
ptr,
length,
0,
0
)
/*
Transfer acquired assets (only needed when working with specific
marketplaces which do not support recipients).
*/
if and(result, eq(shl(0x80, supported), _FLAG)) {
pop(
delegatecall(
gas(),
sload(finalizer.slot),
ptr,
length,
0,
0
)
)
}
}
// Iterate to the next call in the cart.
offset := add(offset, add(length, 0x60))
}
}
}
/**
Return unused payment assets back to the message sender.
@param _payments An array containing information about token addresses and
the total token amounts needed to purchase all orders in the cart.
@param _balances An array containing the balances of payment assets in this
contract.
*/
function _returnLeftovers (
Payment[] calldata _payments,
uint256[] memory _balances
) private {
uint256 current;
for (uint256 i; i < _balances.length; ) {
unchecked {
// Attempt to return Ether.
if (_payments[i].asset == address(0)) {
current = address(this).balance;
if (current > _balances[i]) {
msg.sender.transferEth(current - _balances[i]);
}
// Otherwise, attempt to return an ERC-20 token.
} else {
current = IERC20(_payments[i].asset).balanceOf(
address(this)
);
if (current > _balances[i]) {
IERC20(_payments[i].asset).safeTransfer(
msg.sender,
current - _balances[i]
);
}
}
++i;
}
}
}
/**
Parse the incoming cart, verify payments status, gracefuly execute orders,
and return payments for failed orders.
@param _cart A bytes array containing encoded calls to exchanges with the
exchange, call length, and Ether value as a prefix to each call. For
example:
cart = encode(
exchange, length, value, call,
...
exchange(n), length(n), value(n), call(n)
)
... where n is an index of a call.
@param _payments An array containing information about token addresses and
the total token amounts needed to purchase all orders in the cart.
@custom:throws Paused if purchases on the aggregator have been paused.
*/
function purchase (
bytes calldata _cart,
Payment[] calldata _payments
) external payable nonReentrant {
if (_status == EscapeHatch.Status.Paused) {
revert Paused();
}
// Accumulate the balance of this contract for each payment asset.
uint256[] memory balances = new uint256[](_payments.length);
_readBalances(_payments, balances);
// Gather payment assets to the aggregator.
_gatherPayments(_payments);
// Perform the asset purchase.
_buy(_cart);
// Return leftover balances.
_returnLeftovers(_payments, balances);
}
}
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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.
*
* By default, the owner account will be the one that deploys the contract. 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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @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 {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_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);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized < type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @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);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_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 {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @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());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// 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 This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @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].
*/
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);
}
@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/draft-IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../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.
*
* By default, the owner account will be the one that deploys the contract. 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;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @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 {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing 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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_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);
}
}
@openzeppelin/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
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);
}
@openzeppelin/contracts/security/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @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;
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() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
@openzeppelin/contracts/token/ERC1155/IERC1155.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
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].
*/
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);
}
@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
@openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
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_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
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);
}
}
@openzeppelin/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @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,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode 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 {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]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
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 if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// 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))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode 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 {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
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]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
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.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// 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);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// 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);
}
return (signer, RecoverError.NoError);
}
/**
* @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) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface 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);
}
contracts/access/PermitControl.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.15;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
@title An advanced permission-management contract.
@author Tim Clancy <@_Enoch>
This contract allows for a contract owner to delegate specific rights to
external addresses. Additionally, these rights can be gated behind certain
sets of circumstances and granted expiration times. This is useful for some
more finely-grained access control in contracts.
The owner of this contract is always a fully-permissioned super-administrator.
@custom:date August 23rd, 2021.
*/
abstract contract PermitControl is Ownable {
using Address for address;
/// A special reserved constant for representing no rights.
bytes32 public constant ZERO_RIGHT = hex"00000000000000000000000000000000";
/// A special constant specifying the unique, universal-rights circumstance.
bytes32 public constant UNIVERSAL = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
/**
A special constant specifying the unique manager right. This right allows an
address to freely-manipulate the `managedRight` mapping.
*/
bytes32 public constant MANAGER = hex"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
/**
A mapping of per-address permissions to the circumstances, represented as
an additional layer of generic bytes32 data, under which the addresses have
various permits. A permit in this sense is represented by a per-circumstance
mapping which couples some right, represented as a generic bytes32, to an
expiration time wherein the right may no longer be exercised. An expiration
time of 0 indicates that there is in fact no permit for the specified
address to exercise the specified right under the specified circumstance.
@dev Universal rights MUST be stored under the 0xFFFFFFFFFFFFFFFFFFFFFFFF...
max-integer circumstance. Perpetual rights may be given an expiry time of
max-integer.
*/
mapping ( address => mapping( bytes32 => mapping( bytes32 => uint256 )))
public permissions;
/**
An additional mapping of managed rights to manager rights. This mapping
represents the administrator relationship that various rights have with one
another. An address with a manager right may freely set permits for that
manager right's managed rights. Each right may be managed by only one other
right.
*/
mapping ( bytes32 => bytes32 ) public managerRight;
/**
An event emitted when an address has a permit updated. This event captures,
through its various parameter combinations, the cases of granting a permit,
updating the expiration time of a permit, or revoking a permit.
@param updater The address which has updated the permit.
@param updatee The address whose permit was updated.
@param circumstance The circumstance wherein the permit was updated.
@param role The role which was updated.
@param expirationTime The time when the permit expires.
*/
event PermitUpdated (
address indexed updater,
address indexed updatee,
bytes32 circumstance,
bytes32 indexed role,
uint256 expirationTime
);
/**
An event emitted when a management relationship in `managerRight` is
updated. This event captures adding and revoking management permissions via
observing the update history of the `managerRight` value.
@param manager The address of the manager performing this update.
@param managedRight The right which had its manager updated.
@param managerRight The new manager right which was updated to.
*/
event ManagementUpdated (
address indexed manager,
bytes32 indexed managedRight,
bytes32 indexed managerRight
);
/**
A modifier which allows only the super-administrative owner or addresses
with a specified valid right to perform a call.
@param _circumstance The circumstance under which to check for the validity
of the specified `right`.
@param _right The right to validate for the calling address. It must be
non-expired and exist within the specified `_circumstance`.
*/
modifier hasValidPermit (
bytes32 _circumstance,
bytes32 _right
) {
require(
_msgSender() == owner() || hasRight(_msgSender(), _circumstance, _right),
"P1"
);
_;
}
/**
Set the `_managerRight` whose `UNIVERSAL` holders may freely manage the
specified `_managedRight`.
@param _managedRight The right which is to have its manager set to
`_managerRight`.
@param _managerRight The right whose `UNIVERSAL` holders may manage
`_managedRight`.
*/
function setManagerRight (
bytes32 _managedRight,
bytes32 _managerRight
) external virtual hasValidPermit(UNIVERSAL, MANAGER) {
require(_managedRight != ZERO_RIGHT, "P3");
managerRight[_managedRight] = _managerRight;
emit ManagementUpdated(_msgSender(), _managedRight, _managerRight);
}
/**
Set the permit to a specific address under some circumstances. A permit may
only be set by the super-administrative contract owner or an address holding
some delegated management permit.
@param _address The address to assign the specified `_right` to.
@param _circumstance The circumstance in which the `_right` is valid.
@param _right The specific right to assign.
@param _expirationTime The time when the `_right` expires for the provided
`_circumstance`.
*/
function setPermit (
address _address,
bytes32 _circumstance,
bytes32 _right,
uint256 _expirationTime
) public virtual hasValidPermit(UNIVERSAL, managerRight[_right]) {
require(_right != ZERO_RIGHT, "P2");
permissions[_address][_circumstance][_right] = _expirationTime;
emit PermitUpdated(
_msgSender(),
_address,
_circumstance,
_right,
_expirationTime
);
}
/**
Determine whether or not an address has some rights under the given
circumstance, and if they do have the right, until when.
@param _address The address to check for the specified `_right`.
@param _circumstance The circumstance to check the specified `_right` for.
@param _right The right to check for validity.
@return The timestamp in seconds when the `_right` expires. If the timestamp
is zero, we can assume that the user never had the right.
*/
function hasRightUntil (
address _address,
bytes32 _circumstance,
bytes32 _right
) public view returns (uint256) {
return permissions[_address][_circumstance][_right];
}
/**
Determine whether or not an address has some rights under the given
circumstance,
@param _address The address to check for the specified `_right`.
@param _circumstance The circumstance to check the specified `_right` for.
@param _right The right to check for validity.
@return true or false, whether user has rights and time is valid.
*/
function hasRight (
address _address,
bytes32 _circumstance,
bytes32 _right
) public view returns (bool) {
return permissions[_address][_circumstance][_right] > block.timestamp;
}
}
contracts/aggregator/AggregatorTradeFinalizer.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.15;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "../test/looksrare/LooksRareExchange.sol";
import "../test/x2y2/X2Y2Exchange.sol";
/**
@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
@title GigaMart Aggregated Finalizer
@author Rostislav Khlebnikov <@catpic5buck>
@custom:contributor Tim Clancy <@_Enoch>
This contract implements delegated order finalization for particular
exchanges supported by the multi-market aggregator for GigaMart. In
particular, certain exchanges require the orders to be issued from the
recipient of the item, like X2Y2 and LooksRare.
@custom:version 1.0
@custom:date Januart 24th, 2023.
*/
contract AggregatorTradeFinalizer {
/// A constant for the ERC-721 interface ID.
bytes4 public constant INTERFACE_ID_ERC721 = 0x80ac58cd;
/// Track the slot for a supported exchange.
uint256 private constant _SUPPORTED_EXCHANGES_SLOT = 4;
/// Record the address of X2Y2's exchange.
address private constant _X2Y2_ADDRESS =
0x74312363e45DCaBA76c59ec49a7Aa8A65a67EeD3;
/// Record the address of LooksRare's exchange.
address private constant _LOOKSRARE_ADDRESS =
0x59728544B08AB483533076417FbBB2fD0B17CE3a;
/**
This struct defines an ERC-721 item as a token address and a token ID.
@param token The address of the ERC-721 item contract.
@param tokenId The ID of the ERC-721 item.
*/
struct Pair721 {
IERC721 token;
uint256 tokenId;
}
/**
This struct defines an ERC-1155 item as a token address, token ID, and
amount.
@param token The address of the ERC-1155 item contract.
@param tokenId The ID of the ERC-1155 item.
@param amount The amount of the ERC-1155 item to transfer.
*/
struct Pair1155 {
IERC1155 token;
uint256 tokenId;
uint256 amount;
}
/**
A function to initialize storage for this aggregated trade finalizer.
*/
function initialize () external {
assembly {
mstore(0x00, _LOOKSRARE_ADDRESS)
mstore(0x20, _SUPPORTED_EXCHANGES_SLOT)
let lr_key := keccak256(0x00, 0x40)
mstore(0x00, _X2Y2_ADDRESS)
let x2y2_key := keccak256(0x00, 0x40)
sstore(lr_key, add(sload(lr_key), 1))
sstore(x2y2_key, add(sload(x2y2_key), 1))
}
}
/**
A helper function to replace particular masked values in the `_src` array
*/
function _arrayReplace (
bytes memory _src,
bytes memory _replacement,
bytes memory _mask
) internal pure virtual {
for (uint256 i = 0; i < _src.length; i++) {
if (_mask[i] != 0) {
_src[i] = _replacement[i];
}
}
}
function run(Market.RunInput calldata input) external payable{
for ( uint256 i; i < input.details.length;) {
bytes memory data = input.orders[input.details[i].orderIdx].items[input.details[i].itemIdx].data;
{
if (input.orders[input.details[i].orderIdx].dataMask.length > 0 && input.details[i].dataReplacement.length > 0) {
_arrayReplace(data, input.details[i].dataReplacement, input.orders[input.details[i].orderIdx].dataMask);
}
}
if (data.length == 128){
Pair721[] memory pairs = abi.decode(data, (Pair721[]));
for (uint256 j; j < pairs.length;) {
pairs[j].token.safeTransferFrom(address(this), msg.sender, pairs[j].tokenId);
unchecked {
++j;
}
}
} else {
Pair1155[] memory pairs = abi.decode(data, (Pair1155[]));
for (uint256 j; j < pairs.length;) {
pairs[j].token.safeTransferFrom(address(this), msg.sender, pairs[j].tokenId, pairs[j].amount, "");
unchecked {
++j;
}
}
}
unchecked {
++i;
}
}
}
function matchAskWithTakerBidUsingETHAndWETH(
OrderTypes.TakerOrder calldata,
OrderTypes.MakerOrder calldata makerAsk
) external payable {
if (IERC165(makerAsk.collection).supportsInterface(INTERFACE_ID_ERC721)) {
IERC721(makerAsk.collection).safeTransferFrom(address(this), msg.sender, makerAsk.tokenId);
} else {
IERC1155(makerAsk.collection).safeTransferFrom(address(this), msg.sender, makerAsk.tokenId, makerAsk.amount, "");
}
}
function matchAskWithTakerBid(
OrderTypes.TakerOrder calldata,
OrderTypes.MakerOrder calldata makerAsk
) external payable {
if (IERC165(makerAsk.collection).supportsInterface(INTERFACE_ID_ERC721)) {
IERC721(makerAsk.collection).safeTransferFrom(address(this), msg.sender, makerAsk.tokenId);
} else {
IERC1155(makerAsk.collection).safeTransferFrom(address(this), msg.sender, makerAsk.tokenId, makerAsk.amount, "");
}
}
}contracts/aggregator/lib/Configuration.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.15;
import {
EscapeHatch,
IERC20,
SafeERC20
} from "./EscapeHatch.sol";
import {
AggregatorTradeFinalizer
} from "../AggregatorTradeFinalizer.sol";
/**
@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
@title Configuration
@author Rostislav Khlebnikov <@catpic5buck>
@custom:contributor Tim Clancy <@_Enoch>
This contract contains configuration controls for the GigaMart aggregator.
@custom:date January 23rd, 2023.
*/
abstract contract Configuration is EscapeHatch {
uint256 internal constant _FLAG =
0x0000000000000000000000000000000100000000000000000000000000000000;
/// The identifier for the right to adjust the aggregator configuration.
bytes32 private constant AGGREGATOR_CONFIG = keccak256("AGGREGATOR_CONFIG");
/// A mapping to track flags for supported exchange addresses.
mapping ( address => uint256 ) public supportedExchanges;
/// Store an immutable reference to delegate contract.
AggregatorTradeFinalizer public finalizer;
/**
Construct an instance of the GigaMart aggregator configuration.
@param _exchanges An array of exchange addresses to mark as supported.
@param _tokens An array of payment tokens to approve to `_transferProxies`.
@param _transferProxies An array of addresses to set approval for on behalf
of this contract.
@param _governance The address of a caller which has rights to manage
payment tokens.
@param _rescuer An address that can pause or unpause the contract and
rescue assets.
*/
constructor (
address[] memory _exchanges,
address[] memory _tokens,
address[] memory _transferProxies,
address _governance,
address _rescuer
) EscapeHatch(_rescuer) {
// Immediately flag any provided exchanges as supported.
for (uint256 i; i < _exchanges.length; ) {
supportedExchanges[_exchanges[i]] += _FLAG;
unchecked {
++i;
}
}
// Approve any provided tokens for use on the exchanges.
for (uint256 j; j < _transferProxies.length; ) {
for (uint256 k; k < _tokens.length; ) {
IERC20(_tokens[k]).approve(
_transferProxies[j],
type(uint256).max
);
unchecked {
++k;
}
}
unchecked {
++j;
}
}
// Set the permit of the aggregator configurator.
setPermit(_governance, UNIVERSAL, AGGREGATOR_CONFIG, type(uint256).max);
}
/**
Set and initialize a new aggregation finalizer, used for handling certain
exchanges (LooksRare and X2Y2) which do not support direct recipients of
3rd party purchased items.
@param _finalizer The address of a new aggregation finalizer contract.
*/
function changeFinalizer (
AggregatorTradeFinalizer _finalizer
) external hasValidPermit(UNIVERSAL, AGGREGATOR_CONFIG) {
finalizer = _finalizer;
address(finalizer).delegatecall(abi.encodePacked(bytes4(keccak256("initialize()"))));
}
/**
Set approval on the given array `_tokens` of payment tokens to each
transfer proxy in `_transferProxies`.
@param _tokens An array of payment tokens to approve `transferProxies` to
spend.
@param _transferProxies An array of addresses to set approvals for on
behalf of this contract.
*/
function addPaymentTokens (
address[] calldata _tokens,
address[] calldata _transferProxies
) external hasValidPermit(UNIVERSAL, AGGREGATOR_CONFIG) {
for (uint256 i; i < _transferProxies.length; ) {
for (uint256 j; j < _tokens.length; ) {
// Approve each token on each proxy.
IERC20(_tokens[j]).approve(
_transferProxies[i],
type(uint256).max
);
unchecked {
++j;
}
}
unchecked {
++i;
}
}
}
/**
Revoke approval on the given array `_tokens` of payment tokens from each
transfer proxy in `_transferProxies`.
@param _tokens An array of payment tokens to revoke approval of
`transferProxies` to spend.
@param _transferProxies An array of addresses to revoke approvals from on
behalf of this contract.
*/
function removePaymentTokens (
address[] calldata _tokens,
address[] calldata _transferProxies
) external hasValidPermit(UNIVERSAL, AGGREGATOR_CONFIG) {
for (uint256 i; i < _transferProxies.length; ) {
for (uint256 j; j < _tokens.length; ) {
// Revoke approval for each token on each proxy.
IERC20(_tokens[j]).approve(_transferProxies[i], 0);
unchecked {
++j;
}
}
unchecked {
++i;
}
}
}
/**
Include `_exchange` for order aggregation.
@param _exchange An array of payment tokens to revoke approval of
`transferProxies` to spend.
*/
function addExchange (
address _exchange
) external hasValidPermit(UNIVERSAL, AGGREGATOR_CONFIG) {
supportedExchanges[_exchange] += _FLAG;
}
/**
Exclude `_exchange` from order aggregation.
@param _exchange An array of payment tokens to revoke approval of
`transferProxies` to spend.
*/
function removeExchange (
address _exchange
) external hasValidPermit(UNIVERSAL, AGGREGATOR_CONFIG) {
supportedExchanges[_exchange] = 0;
}
}
contracts/aggregator/lib/EscapeHatch.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.15;
import {
IERC721
} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {
IERC1155
} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {
IERC20,
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {
PermitControl
} from "../../access/PermitControl.sol";
/**
Thrown in the event that attempting to rescue an asset from the contract
fails.
@param index The index of the asset whose rescue failed.
*/
error RescueFailed (uint256 index);
/**
@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
@title Escape Hatch
@author Rostislav Khlebnikov <@catpic5buck>
@custom:contributor Tim Clancy <@_Enoch>
This contract contains logic for pausing contract operations during updates
and a backup mechanism for user assets restoration.
@custom:date December 4th, 2022.
*/
abstract contract EscapeHatch is PermitControl {
using SafeERC20 for IERC20;
/// The public identifier for the right to rescue assets.
bytes32 internal constant ASSET_RESCUER = keccak256("ASSET_RESCUER");
/**
An enum type representing the status of the contract being escaped.
@param None A default value used to avoid setting storage unnecessarily.
@param Unpaused The contract is unpaused.
@param Paused The contract is paused.
*/
enum Status {
None,
Unpaused,
Paused
}
/**
An enum type representing the type of asset this contract may be dealing
with.
@param Native The type for Ether.
@param ERC20 The type for an ERC-20 token.
@param ERC721 The type for an ERC-721 token.
@param ERC1155 The type for an ERC-1155 token.
*/
enum AssetType {
Native,
ERC20,
ERC721,
ERC1155
}
/**
A struct containing information about a particular asset transfer.
@param assetType The type of the asset involved.
@param asset The address of the asset.
@param id The ID of the asset.
@param amount The amount of asset being transferred.
@param to The destination address where the asset is being sent.
*/
struct Asset {
AssetType assetType;
address asset;
uint256 id;
uint256 amount;
address to;
}
/// A flag to track whether or not the contract is paused.
Status internal _status = Status.Unpaused;
/**
Construct a new instance of an escape hatch, which supports pausing and the
rescue of trapped assets.
@param _rescuer The address of the rescuer caller that can pause, unpause,
and rescue assets.
*/
constructor (
address _rescuer
) {
// Set the permit for the rescuer.
setPermit(_rescuer, UNIVERSAL, ASSET_RESCUER, type(uint256).max);
}
/// An administrative function to pause the contract.
function pause () external hasValidPermit(UNIVERSAL, ASSET_RESCUER) {
_status = Status.Paused;
}
/// An administrative function to resume the contract.
function unpause () external hasValidPermit(UNIVERSAL, ASSET_RESCUER) {
_status = Status.Unpaused;
}
/**
An admin function used in emergency situations to transfer assets from this
contract if they get stuck.
@param _assets An array of `Asset` structs to attempt transfers.
@custom:throws RescueFailed if an Ether asset could not be rescued.
*/
function rescueAssets (
Asset[] calldata _assets
) external hasValidPermit(UNIVERSAL, ASSET_RESCUER) {
for (uint256 i; i < _assets.length; ) {
// If the asset is Ether, attempt a rescue; skip on reversion.
if (_assets[i].assetType == AssetType.Native) {
(bool result, ) = _assets[i].to.call{ value: _assets[i].amount }("");
if (!result) {
revert RescueFailed(i);
}
unchecked {
++i;
}
continue;
}
// Attempt to rescue ERC-20 items.
if (_assets[i].assetType == AssetType.ERC20) {
IERC20(_assets[i].asset).safeTransfer(
_assets[i].to,
_assets[i].amount
);
}
// Attempt to rescue ERC-721 items.
if (_assets[i].assetType == AssetType.ERC721) {
IERC721(_assets[i].asset).transferFrom(
address(this),
_assets[i].to,
_assets[i].id
);
}
// Attempt to rescue ERC-1155 items.
if (_assets[i].assetType == AssetType.ERC1155) {
IERC1155(_assets[i].asset).safeTransferFrom(
address(this),
_assets[i].to,
_assets[i].id,
_assets[i].amount,
""
);
}
unchecked {
++i;
}
}
}
}
contracts/marketplace/interfaces/IProxyRegistry.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.15;
/// Thrown if a caller is not authorized in the proxy registry.
error NonAuthorizedCaller ();
/**
@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
@title Ownable Delegate Proxy
@author Protinam, Project Wyvern
@author Tim Clancy <@_Enoch>
@author Rostislav Khlebnikov <@catpic5buck>
A proxy registry contract. This contract was originally developed
by Project Wyvern. It has been modified to support a more modern version of
Solidity with associated best practices. The documentation has also been
improved to provide more clarity.
@custom:date December 4th, 2022.
*/
interface IProxyRegistry {
/// Return the address of tje current valid implementation of delegate proxy.
function delegateProxyImplementation () external view returns (address);
/**
Returns the address of a proxy which was registered for the user address
before listing items.
@param _owner The address of items lister.
*/
function proxies (
address _owner
) external view returns (address);
/**
Returns true if the `_caller` to the proxy registry is eligible and
registered.
@param _caller The address of the caller.
*/
function authorizedCallers (
address _caller
) external view returns (bool);
/**
Returns the address of the `_caller`'s proxy and current implementation
address.
@param _caller The address of the caller.
*/
function userProxyConfig (
address _caller
) external view returns (address, address);
/**
Enables an address to register its own proxy contract with this registry.
@return _ The new contract with its implementation.
*/
function registerProxy () external returns (address);
}
contracts/marketplace/libraries/NativeTransfer.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.15;
/// Emitted in the event that transfer of Ether fails.
error TransferFailed ();
/**
@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
@title Native Ether Transfer Library
@author Rostislav Khlebnikov <@catpic5buck>
@custom:contributor Tim Clancy <@_Enoch>
A library for safely conducting Ether transfers and verifying success.
@custom:date December 4th, 2022.
*/
library NativeTransfer {
/**
A helper function for wrapping a low-level Ether transfer call with modern
error reversion.
@param _to The address to send Ether to.
@param _value The value of Ether to send to `_to`.
@custom:throws TransferFailed if the transfer of Ether fails.
*/
function transferEth (
address _to,
uint _value
) internal {
(bool success, ) = _to.call{ value: _value }("");
if (!success) {
revert TransferFailed();
}
}
}
contracts/marketplace/proxy/TokenTransferProxy.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.15;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IProxyRegistry.sol";
/**
@custom:benediction DEVS BENEDICAT ET PROTEGAT CONTRACTVS MEAM
@title Token Transfer Proxy
@author Project Wyvern Developers
@author Tim Clancy <@_Enoch>
@custom:contributor Rostislav Khlebnikov <@catpic5buck>
A token transfer proxy contract. This contract was originally developed by
Project Wyvern. It has been modified to support a more modern version of
Solidity with associated best practices. The documentation has also been
improved to provide more clarity.
@custom:date December 4th, 2022.
*/
contract TokenTransferProxy {
using SafeERC20 for IERC20;
/// The address of the immutable authentication registry.
IProxyRegistry public immutable registry;
/**
Construct a new instance of this token transfer proxy given the associated
registry.
@param _registry The address of a proxy registry.
*/
constructor (
address _registry
) {
registry = IProxyRegistry(_registry);
}
/**
Perform a transfer on a targeted ERC-20 token, rejecting unauthorized callers.
@param _token The address of the ERC-20 token to transfer.
@param _from The address to transfer ERC-20 tokens from.
@param _to The address to transfer ERC-20 tokens to.
@param _amount The amount of ERC-20 tokens to transfer.
@custom:throws NonAuthorizedCaller if the caller is not authorized to
perform the ERC-20 token transfer.
*/
function transferERC20 (
address _token,
address _from,
address _to,
uint _amount
) public {
if (!registry.authorizedCallers(msg.sender)) {
revert NonAuthorizedCaller();
}
IERC20(_token).safeTransferFrom(_from, _to, _amount);
}
}
contracts/test/looksrare/LooksRareExchange.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// OpenZeppelin contracts
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// LooksRare interfaces
import {ICurrencyManager} from "./interfaces/ICurrencyManager.sol";
import {IExecutionManager} from "./interfaces/IExecutionManager.sol";
import {IExecutionStrategy} from "./interfaces/IExecutionStrategy.sol";
import {IRoyaltyFeeManager} from "./interfaces/IRoyaltyFeeManager.sol";
import {ILooksRareExchange} from "./interfaces/ILooksRareExchange.sol";
import {ITransferManagerNFT} from "./interfaces/ITransferManagerNFT.sol";
import {ITransferSelectorNFT} from "./interfaces/ITransferSelectorNFT.sol";
import {IWETH} from "./interfaces/IWETH.sol";
// LooksRare libraries
import {OrderTypes} from "./libraries/OrderTypes.sol";
import {SignatureChecker} from "./libraries/SignatureChecker.sol";
/**
* @title LooksRareExchange
* @notice It is the core contract of the LooksRare exchange.
LOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSRAR'''''''''''''''''''''''''''''''''''OOKSRLOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKS:. .;OOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOO,. .,KSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRAREL' ..',;:LOOKS::;,'.. 'RARELOOKSRARELOOKSR
LOOKSRARELOOKSRAR. .,:LOOKSRARELOOKSRARELO:,. .RELOOKSRARELOOKSR
LOOKSRARELOOKS:. .;RARELOOKSRARELOOKSRARELOOKSl;. .:OOKSRARELOOKSR
LOOKSRARELOO;. .'OKSRARELOOKSRARELOOKSRARELOOKSRARE'. .;KSRARELOOKSR
LOOKSRAREL,. .,LOOKSRARELOOK:;;:"""":;;;lELOOKSRARELO,. .,RARELOOKSR
LOOKSRAR. .;okLOOKSRAREx:. .;OOKSRARELOOK;. .RELOOKSR
LOOKS:. .:dOOOLOOKSRARE' .''''.. .OKSRARELOOKSR:. .LOOKSR
LOx;. .cKSRARELOOKSRAR' 'LOOKSRAR' .KSRARELOOKSRARc.. .OKSR
L;. .cxOKSRARELOOKSRAR. .LOOKS.RARE' ;kRARELOOKSRARExc. .;R
LO' .;oOKSRARELOOKSRAl. .LOOKS.RARE. :kRARELOOKSRAREo;. 'SR
LOOK;. .,KSRARELOOKSRAx, .;LOOKSR;. .oSRARELOOKSRAo,. .;OKSR
LOOKSk:. .'RARELOOKSRARd;. .... 'oOOOOOOOOOOxc'. .:LOOKSR
LOOKSRARc. .:dLOOKSRAREko;. .,lxOOOOOOOOOd:. .ARELOOKSR
LOOKSRARELo' .;oOKSRARELOOxoc;,....,;:ldkOOOOOOOOkd;. 'SRARELOOKSR
LOOKSRARELOOd,. .,lSRARELOOKSRARELOOKSRARELOOKSRkl,. .,OKSRARELOOKSR
LOOKSRARELOOKSx;. ..;oxELOOKSRARELOOKSRARELOkxl:.. .:LOOKSRARELOOKSR
LOOKSRARELOOKSRARc. .':cOKSRARELOOKSRALOc;'. .ARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELl' ...'',,,,''... 'SRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOo,. .,OKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSx;. .;xOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSRLO:. .:SRLOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSRLOOKl. .lOKSRLOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSRLOOKSRo'. .'oLOOKSRLOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSRLOOKSRARd;. .;xRELOOKSRLOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSRLOOKSRARELO:. .:kRARELOOKSRLOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKl. .cOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRo' 'oLOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRARE,. .,dRELOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSR
LOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSRARELOOKSRARELOOKSRLOOKSRARELOOKSRARELOOKSR
*/
contract LooksRareExchange is ILooksRareExchange, ReentrancyGuard, Ownable {
using SafeERC20 for IERC20;
using OrderTypes for OrderTypes.MakerOrder;
using OrderTypes for OrderTypes.TakerOrder;
address public immutable WETH;
bytes32 public immutable DOMAIN_SEPARATOR;
address public protocolFeeRecipient;
ICurrencyManager public currencyManager;
IExecutionManager public executionManager;
IRoyaltyFeeManager public royaltyFeeManager;
ITransferSelectorNFT public transferSelectorNFT;
mapping(address => uint256) public userMinOrderNonce;
mapping(address => mapping(uint256 => bool)) private _isUserOrderNonceExecutedOrCancelled;
event CancelAllOrders(address indexed user, uint256 newMinNonce);
event CancelMultipleOrders(address indexed user, uint256[] orderNonces);
event NewCurrencyManager(address indexed currencyManager);
event NewExecutionManager(address indexed executionManager);
event NewProtocolFeeRecipient(address indexed protocolFeeRecipient);
event NewRoyaltyFeeManager(address indexed royaltyFeeManager);
event NewTransferSelectorNFT(address indexed transferSelectorNFT);
event RoyaltyPayment(
address indexed collection,
uint256 indexed tokenId,
address indexed royaltyRecipient,
address currency,
uint256 amount
);
event TakerAsk(
bytes32 orderHash, // bid hash of the maker order
uint256 orderNonce, // user order nonce
address indexed taker, // sender address for the taker ask order
address indexed maker, // maker address of the initial bid order
address indexed strategy, // strategy that defines the execution
address currency, // currency address
address collection, // collection address
uint256 tokenId, // tokenId transferred
uint256 amount, // amount of tokens transferred
uint256 price // final transacted price
);
event TakerBid(
bytes32 orderHash, // ask hash of the maker order
uint256 orderNonce, // user order nonce
address indexed taker, // sender address for the taker bid order
address indexed maker, // maker address of the initial ask order
address indexed strategy, // strategy that defines the execution
address currency, // currency address
address collection, // collection address
uint256 tokenId, // tokenId transferred
uint256 amount, // amount of tokens transferred
uint256 price // final transacted price
);
/**
* @notice Constructor
* @param _currencyManager currency manager address
* @param _executionManager execution manager address
* @param _royaltyFeeManager royalty fee manager address
* @param _WETH wrapped ether address (for other chains, use wrapped native asset)
* @param _protocolFeeRecipient protocol fee recipient
*/
constructor(
address _currencyManager,
address _executionManager,
address _royaltyFeeManager,
address _WETH,
address _protocolFeeRecipient
) {
// Calculate the domain separator
DOMAIN_SEPARATOR = keccak256(
abi.encode(
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
0xda9101ba92939daf4bb2e18cd5f942363b9297fbc3232c9dd964abb1fb70ed71, // keccak256("LooksRareExchange")
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, // keccak256(bytes("1")) for versionId = 1
block.chainid,
address(this)
)
);
currencyManager = ICurrencyManager(_currencyManager);
executionManager = IExecutionManager(_executionManager);
royaltyFeeManager = IRoyaltyFeeManager(_royaltyFeeManager);
WETH = _WETH;
protocolFeeRecipient = _protocolFeeRecipient;
}
/**
* @notice Cancel all pending orders for a sender
* @param minNonce minimum user nonce
*/
function cancelAllOrdersForSender(uint256 minNonce) external {
require(minNonce > userMinOrderNonce[msg.sender], "Cancel: Order nonce lower than current");
require(minNonce < userMinOrderNonce[msg.sender] + 500000, "Cancel: Cannot cancel more orders");
userMinOrderNonce[msg.sender] = minNonce;
emit CancelAllOrders(msg.sender, minNonce);
}
/**
* @notice Cancel maker orders
* @param orderNonces array of order nonces
*/
function cancelMultipleMakerOrders(uint256[] calldata orderNonces) external {
require(orderNonces.length > 0, "Cancel: Cannot be empty");
for (uint256 i = 0; i < orderNonces.length; i++) {
require(orderNonces[i] >= userMinOrderNonce[msg.sender], "Cancel: Order nonce lower than current");
_isUserOrderNonceExecutedOrCancelled[msg.sender][orderNonces[i]] = true;
}
emit CancelMultipleOrders(msg.sender, orderNonces);
}
/**
* @notice Match ask with a taker bid order using ETH
* @param takerBid taker bid order
* @param makerAsk maker ask order
*/
function matchAskWithTakerBidUsingETHAndWETH(
OrderTypes.TakerOrder calldata takerBid,
OrderTypes.MakerOrder calldata makerAsk
) external payable override nonReentrant {
require((makerAsk.isOrderAsk) && (!takerBid.isOrderAsk), "Order: Wrong sides");
require(makerAsk.currency == WETH, "Order: Currency must be WETH");
require(msg.sender == takerBid.taker, "Order: Taker must be the sender");
// If not enough ETH to cover the price, use WETH
if (takerBid.price > msg.value) {
IERC20(WETH).safeTransferFrom(msg.sender, address(this), (takerBid.price - msg.value));
} else {
require(takerBid.price == msg.value, "Order: Msg.value too high");
}
// Wrap ETH sent to this contract
IWETH(WETH).deposit{value: msg.value}();
// Check the maker ask order
bytes32 askHash = makerAsk.hash();
_validateOrder(makerAsk, askHash);
// Retrieve execution parameters
(bool isExecutionValid, uint256 tokenId, uint256 amount) = IExecutionStrategy(makerAsk.strategy)
.canExecuteTakerBid(takerBid, makerAsk);
require(isExecutionValid, "Strategy: Execution invalid");
// Update maker ask order status to true (prevents replay)
_isUserOrderNonceExecutedOrCancelled[makerAsk.signer][makerAsk.nonce] = true;
// Execution part 1/2
_transferFeesAndFundsWithWETH(
makerAsk.strategy,
makerAsk.collection,
tokenId,
makerAsk.signer,
takerBid.price,
makerAsk.minPercentageToAsk
);
// Execution part 2/2
_transferNonFungibleToken(makerAsk.collection, makerAsk.signer, takerBid.taker, tokenId, amount);
emit TakerBid(
askHash,
makerAsk.nonce,
takerBid.taker,
makerAsk.signer,
makerAsk.strategy,
makerAsk.currency,
makerAsk.collection,
tokenId,
amount,
takerBid.price
);
}
/**
* @notice Match a takerBid with a matchAsk
* @param takerBid taker bid order
* @param makerAsk maker ask order
*/
function matchAskWithTakerBid(OrderTypes.TakerOrder calldata takerBid, OrderTypes.MakerOrder calldata makerAsk)
external
override
nonReentrant
{
require((makerAsk.isOrderAsk) && (!takerBid.isOrderAsk), "Order: Wrong sides");
require(msg.sender == takerBid.taker, "Order: Taker must be the sender");
// Check the maker ask order
bytes32 askHash = makerAsk.hash();
_validateOrder(makerAsk, askHash);
(bool isExecutionValid, uint256 tokenId, uint256 amount) = IExecutionStrategy(makerAsk.strategy)
.canExecuteTakerBid(takerBid, makerAsk);
require(isExecutionValid, "Strategy: Execution invalid");
// Update maker ask order status to true (prevents replay)
_isUserOrderNonceExecutedOrCancelled[makerAsk.signer][makerAsk.nonce] = true;
// Execution part 1/2
_transferFeesAndFunds(
makerAsk.strategy,
makerAsk.collection,
tokenId,
makerAsk.currency,
msg.sender,
makerAsk.signer,
takerBid.price,
makerAsk.minPercentageToAsk
);
// Execution part 2/2
_transferNonFungibleToken(makerAsk.collection, makerAsk.signer, takerBid.taker, tokenId, amount);
emit TakerBid(
askHash,
makerAsk.nonce,
takerBid.taker,
makerAsk.signer,
makerAsk.strategy,
makerAsk.currency,
makerAsk.collection,
tokenId,
amount,
takerBid.price
);
}
/**
* @notice Match a takerAsk with a makerBid
* @param takerAsk taker ask order
* @param makerBid maker bid order
*/
function matchBidWithTakerAsk(OrderTypes.TakerOrder calldata takerAsk, OrderTypes.MakerOrder calldata makerBid)
external
override
nonReentrant
{
require((!makerBid.isOrderAsk) && (takerAsk.isOrderAsk), "Order: Wrong sides");
require(msg.sender == takerAsk.taker, "Order: Taker must be the sender");
// Check the maker bid order
bytes32 bidHash = makerBid.hash();
_validateOrder(makerBid, bidHash);
(bool isExecutionValid, uint256 tokenId, uint256 amount) = IExecutionStrategy(makerBid.strategy)
.canExecuteTakerAsk(takerAsk, makerBid);
require(isExecutionValid, "Strategy: Execution invalid");
// Update maker bid order status to true (prevents replay)
_isUserOrderNonceExecutedOrCancelled[makerBid.signer][makerBid.nonce] = true;
// Execution part 1/2
_transferNonFungibleToken(makerBid.collection, msg.sender, makerBid.signer, tokenId, amount);
// Execution part 2/2
_transferFeesAndFunds(
makerBid.strategy,
makerBid.collection,
tokenId,
makerBid.currency,
makerBid.signer,
takerAsk.taker,
takerAsk.price,
takerAsk.minPercentageToAsk
);
emit TakerAsk(
bidHash,
makerBid.nonce,
takerAsk.taker,
makerBid.signer,
makerBid.strategy,
makerBid.currency,
makerBid.collection,
tokenId,
amount,
takerAsk.price
);
}
/**
* @notice Update currency manager
* @param _currencyManager new currency manager address
*/
function updateCurrencyManager(address _currencyManager) external onlyOwner {
require(_currencyManager != address(0), "Owner: Cannot be null address");
currencyManager = ICurrencyManager(_currencyManager);
emit NewCurrencyManager(_currencyManager);
}
/**
* @notice Update execution manager
* @param _executionManager new execution manager address
*/
function updateExecutionManager(address _executionManager) external onlyOwner {
require(_executionManager != address(0), "Owner: Cannot be null address");
executionManager = IExecutionManager(_executionManager);
emit NewExecutionManager(_executionManager);
}
/**
* @notice Update protocol fee and recipient
* @param _protocolFeeRecipient new recipient for protocol fees
*/
function updateProtocolFeeRecipient(address _protocolFeeRecipient) external onlyOwner {
protocolFeeRecipient = _protocolFeeRecipient;
emit NewProtocolFeeRecipient(_protocolFeeRecipient);
}
/**
* @notice Update royalty fee manager
* @param _royaltyFeeManager new fee manager address
*/
function updateRoyaltyFeeManager(address _royaltyFeeManager) external onlyOwner {
require(_royaltyFeeManager != address(0), "Owner: Cannot be null address");
royaltyFeeManager = IRoyaltyFeeManager(_royaltyFeeManager);
emit NewRoyaltyFeeManager(_royaltyFeeManager);
}
/**
* @notice Update transfer selector NFT
* @param _transferSelectorNFT new transfer selector address
*/
function updateTransferSelectorNFT(address _transferSelectorNFT) external onlyOwner {
require(_transferSelectorNFT != address(0), "Owner: Cannot be null address");
transferSelectorNFT = ITransferSelectorNFT(_transferSelectorNFT);
emit NewTransferSelectorNFT(_transferSelectorNFT);
}
/**
* @notice Check whether user order nonce is executed or cancelled
* @param user address of user
* @param orderNonce nonce of the order
*/
function isUserOrderNonceExecutedOrCancelled(address user, uint256 orderNonce) external view returns (bool) {
return _isUserOrderNonceExecutedOrCancelled[user][orderNonce];
}
/**
* @notice Transfer fees and funds to royalty recipient, protocol, and seller
* @param strategy address of the execution strategy
* @param collection non fungible token address for the transfer
* @param tokenId tokenId
* @param currency currency being used for the purchase (e.g., WETH/USDC)
* @param from sender of the funds
* @param to seller's recipient
* @param amount amount being transferred (in currency)
* @param minPercentageToAsk minimum percentage of the gross amount that goes to ask
*/
function _transferFeesAndFunds(
address strategy,
address collection,
uint256 tokenId,
address currency,
address from,
address to,
uint256 amount,
uint256 minPercentageToAsk
) internal {
// Initialize the final amount that is transferred to seller
uint256 finalSellerAmount = amount;
// 1. Protocol fee
{
uint256 protocolFeeAmount = _calculateProtocolFee(strategy, amount);
// Check if the protocol fee is different than 0 for this strategy
if ((protocolFeeRecipient != address(0)) && (protocolFeeAmount != 0)) {
IERC20(currency).safeTransferFrom(from, protocolFeeRecipient, protocolFeeAmount);
finalSellerAmount -= protocolFeeAmount;
}
}
// 2. Royalty fee
{
(address royaltyFeeRecipient, uint256 royaltyFeeAmount) = royaltyFeeManager
.calculateRoyaltyFeeAndGetRecipient(collection, tokenId, amount);
// Check if there is a royalty fee and that it is different to 0
if ((royaltyFeeRecipient != address(0)) && (royaltyFeeAmount != 0)) {
IERC20(currency).safeTransferFrom(from, royaltyFeeRecipient, royaltyFeeAmount);
finalSellerAmount -= royaltyFeeAmount;
emit RoyaltyPayment(collection, tokenId, royaltyFeeRecipient, currency, royaltyFeeAmount);
}
}
require((finalSellerAmount * 10000) >= (minPercentageToAsk * amount), "Fees: Higher than expected");
// 3. Transfer final amount (post-fees) to seller
{
IERC20(currency).safeTransferFrom(from, to, finalSellerAmount);
}
}
/**
* @notice Transfer fees and funds to royalty recipient, protocol, and seller
* @param strategy address of the execution strategy
* @param collection non fungible token address for the transfer
* @param tokenId tokenId
* @param to seller's recipient
* @param amount amount being transferred (in currency)
* @param minPercentageToAsk minimum percentage of the gross amount that goes to ask
*/
function _transferFeesAndFundsWithWETH(
address strategy,
address collection,
uint256 tokenId,
address to,
uint256 amount,
uint256 minPercentageToAsk
) internal {
// Initialize the final amount that is transferred to seller
uint256 finalSellerAmount = amount;
// 1. Protocol fee
{
uint256 protocolFeeAmount = _calculateProtocolFee(strategy, amount);
// Check if the protocol fee is different than 0 for this strategy
if ((protocolFeeRecipient != address(0)) && (protocolFeeAmount != 0)) {
IERC20(WETH).safeTransfer(protocolFeeRecipient, protocolFeeAmount);
finalSellerAmount -= protocolFeeAmount;
}
}
// 2. Royalty fee
{
(address royaltyFeeRecipient, uint256 royaltyFeeAmount) = royaltyFeeManager
.calculateRoyaltyFeeAndGetRecipient(collection, tokenId, amount);
// Check if there is a royalty fee and that it is different to 0
if ((royaltyFeeRecipient != address(0)) && (royaltyFeeAmount != 0)) {
IERC20(WETH).safeTransfer(royaltyFeeRecipient, royaltyFeeAmount);
finalSellerAmount -= royaltyFeeAmount;
emit RoyaltyPayment(collection, tokenId, royaltyFeeRecipient, address(WETH), royaltyFeeAmount);
}
}
require((finalSellerAmount * 10000) >= (minPercentageToAsk * amount), "Fees: Higher than expected");
// 3. Transfer final amount (post-fees) to seller
{
IERC20(WETH).safeTransfer(to, finalSellerAmount);
}
}
/**
* @notice Transfer NFT
* @param collection address of the token collection
* @param from address of the sender
* @param to address of the recipient
* @param tokenId tokenId
* @param amount amount of tokens (1 for ERC721, 1+ for ERC1155)
* @dev For ERC721, amount is not used
*/
function _transferNonFungibleToken(
address collection,
address from,
address to,
uint256 tokenId,
uint256 amount
) internal {
// Retrieve the transfer manager address
address transferManager = transferSelectorNFT.checkTransferManagerForToken(collection);
// If no transfer manager found, it returns address(0)
require(transferManager != address(0), "Transfer: No NFT transfer manager available");
// If one is found, transfer the token
ITransferManagerNFT(transferManager).transferNonFungibleToken(collection, from, to, tokenId, amount);
}
/**
* @notice Calculate protocol fee for an execution strategy
* @param executionStrategy strategy
* @param amount amount to transfer
*/
function _calculateProtocolFee(address executionStrategy, uint256 amount) internal view returns (uint256) {
uint256 protocolFee = IExecutionStrategy(executionStrategy).viewProtocolFee();
return (protocolFee * amount) / 10000;
}
/**
* @notice Verify the validity of the maker order
* @param makerOrder maker order
* @param orderHash computed hash for the order
*/
function _validateOrder(OrderTypes.MakerOrder calldata makerOrder, bytes32 orderHash) internal view {
// Verify whether order nonce has expired
require(
(!_isUserOrderNonceExecutedOrCancelled[makerOrder.signer][makerOrder.nonce]) &&
(makerOrder.nonce >= userMinOrderNonce[makerOrder.signer]),
"Order: Matching order expired"
);
// Verify the signer is not address(0)
require(makerOrder.signer != address(0), "Order: Invalid signer");
// Verify the amount is not 0
require(makerOrder.amount > 0, "Order: Amount cannot be 0");
// Verify the validity of the signature
require(
SignatureChecker.verify(
orderHash,
makerOrder.signer,
makerOrder.v,
makerOrder.r,
makerOrder.s,
DOMAIN_SEPARATOR
),
"Signature: Invalid"
);
// Verify whether the currency is whitelisted
require(currencyManager.isCurrencyWhitelisted(makerOrder.currency), "Currency: Not whitelisted");
// Verify whether strategy can be executed
require(executionManager.isStrategyWhitelisted(makerOrder.strategy), "Strategy: Not whitelisted");
}
}
contracts/test/looksrare/interfaces/ICurrencyManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ICurrencyManager {
function addCurrency(address currency) external;
function removeCurrency(address currency) external;
function isCurrencyWhitelisted(address currency) external view returns (bool);
function viewWhitelistedCurrencies(uint256 cursor, uint256 size) external view returns (address[] memory, uint256);
function viewCountWhitelistedCurrencies() external view returns (uint256);
}
contracts/test/looksrare/interfaces/IExecutionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IExecutionManager {
function addStrategy(address strategy) external;
function removeStrategy(address strategy) external;
function isStrategyWhitelisted(address strategy) external view returns (bool);
function viewWhitelistedStrategies(uint256 cursor, uint256 size) external view returns (address[] memory, uint256);
function viewCountWhitelistedStrategies() external view returns (uint256);
}
contracts/test/looksrare/interfaces/IExecutionStrategy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {OrderTypes} from "../libraries/OrderTypes.sol";
interface IExecutionStrategy {
function canExecuteTakerAsk(OrderTypes.TakerOrder calldata takerAsk, OrderTypes.MakerOrder calldata makerBid)
external
view
returns (
bool,
uint256,
uint256
);
function canExecuteTakerBid(OrderTypes.TakerOrder calldata takerBid, OrderTypes.MakerOrder calldata makerAsk)
external
view
returns (
bool,
uint256,
uint256
);
function viewProtocolFee() external view returns (uint256);
}
contracts/test/looksrare/interfaces/ILooksRareExchange.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {OrderTypes} from "../libraries/OrderTypes.sol";
interface ILooksRareExchange {
function matchAskWithTakerBidUsingETHAndWETH(
OrderTypes.TakerOrder calldata takerBid,
OrderTypes.MakerOrder calldata makerAsk
) external payable;
function matchAskWithTakerBid(OrderTypes.TakerOrder calldata takerBid, OrderTypes.MakerOrder calldata makerAsk)
external;
function matchBidWithTakerAsk(OrderTypes.TakerOrder calldata takerAsk, OrderTypes.MakerOrder calldata makerBid)
external;
}
contracts/test/looksrare/interfaces/IRoyaltyFeeManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IRoyaltyFeeManager {
function calculateRoyaltyFeeAndGetRecipient(
address collection,
uint256 tokenId,
uint256 amount
) external view returns (address, uint256);
}
contracts/test/looksrare/interfaces/ITransferManagerNFT.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITransferManagerNFT {
function transferNonFungibleToken(
address collection,
address from,
address to,
uint256 tokenId,
uint256 amount
) external;
}
contracts/test/looksrare/interfaces/ITransferSelectorNFT.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITransferSelectorNFT {
function checkTransferManagerForToken(address collection) external view returns (address);
}
contracts/test/looksrare/interfaces/IWETH.sol
// SPDX-License-Identifier: GNU
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
contracts/test/looksrare/libraries/OrderTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title OrderTypes
* @notice This library contains order types for the LooksRare exchange.
*/
library OrderTypes {
// keccak256("MakerOrder(bool isOrderAsk,address signer,address collection,uint256 price,uint256 tokenId,uint256 amount,address strategy,address currency,uint256 nonce,uint256 startTime,uint256 endTime,uint256 minPercentageToAsk,bytes params)")
bytes32 internal constant MAKER_ORDER_HASH = 0x40261ade532fa1d2c7293df30aaadb9b3c616fae525a0b56d3d411c841a85028;
struct MakerOrder {
bool isOrderAsk; // true --> ask / false --> bid
address signer; // signer of the maker order
address collection; // collection address
uint256 price; // price (used as )
uint256 tokenId; // id of the token
uint256 amount; // amount of tokens to sell/purchase (must be 1 for ERC721, 1+ for ERC1155)
address strategy; // strategy for trade execution (e.g., DutchAuction, StandardSaleForFixedPrice)
address currency; // currency (e.g., WETH)
uint256 nonce; // order nonce (must be unique unless new maker order is meant to override existing one e.g., lower ask price)
uint256 startTime; // startTime in timestamp
uint256 endTime; // endTime in timestamp
uint256 minPercentageToAsk; // slippage protection (9000 --> 90% of the final price must return to ask)
bytes params; // additional parameters
uint8 v; // v: parameter (27 or 28)
bytes32 r; // r: parameter
bytes32 s; // s: parameter
}
struct TakerOrder {
bool isOrderAsk; // true --> ask / false --> bid
address taker; // msg.sender
uint256 price; // final price for the purchase
uint256 tokenId;
uint256 minPercentageToAsk; // // slippage protection (9000 --> 90% of the final price must return to ask)
bytes params; // other params (e.g., tokenId)
}
function hash(MakerOrder memory makerOrder) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
MAKER_ORDER_HASH,
makerOrder.isOrderAsk,
makerOrder.signer,
makerOrder.collection,
makerOrder.price,
makerOrder.tokenId,
makerOrder.amount,
makerOrder.strategy,
makerOrder.currency,
makerOrder.nonce,
makerOrder.startTime,
makerOrder.endTime,
makerOrder.minPercentageToAsk,
keccak256(makerOrder.params)
)
);
}
}
contracts/test/looksrare/libraries/SignatureChecker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
/**
* @title SignatureChecker
* @notice This library allows verification of signatures for both EOAs and contracts.
*/
library SignatureChecker {
/**
* @notice Recovers the signer of a signature (for EOA)
* @param hash the hash containing the signed mesage
* @param v parameter (27 or 28). This prevents maleability since the public key recovery equation has two possible solutions.
* @param r parameter
* @param s parameter
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// https://ethereum.stackexchange.com/questions/83174/is-it-best-practice-to-check-signature-malleability-in-ecrecover
// https://crypto.iacr.org/2019/affevents/wac/medias/Heninger-BiasedNonceSense.pdf
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"Signature: Invalid s parameter"
);
require(v == 27 || v == 28, "Signature: Invalid v parameter");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "Signature: Invalid signer");
return signer;
}
/**
* @notice Returns whether the signer matches the signed message
* @param hash the hash containing the signed mesage
* @param signer the signer address to confirm message validity
* @param v parameter (27 or 28)
* @param r parameter
* @param s parameter
* @param domainSeparator paramer to prevent signature being executed in other chains and environments
* @return true --> if valid // false --> if invalid
*/
function verify(
bytes32 hash,
address signer,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 domainSeparator
) internal view returns (bool) {
// \x19\x01 is the standardized encoding prefix
// https://eips.ethereum.org/EIPS/eip-712#specification
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hash));
if (Address.isContract(signer)) {
// 0x1626ba7e is the interfaceId for signature contracts (see IERC1271)
return IERC1271(signer).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e;
} else {
return recover(digest, v, r, s) == signer;
}
}
}
contracts/test/x2y2/IDelegate.sol
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.0;
pragma abicoder v2;
interface IDelegate {
function delegateType() external view returns (uint256);
function executeSell(
address seller,
address buyer,
bytes calldata data
) external returns (bool);
function executeBuy(
address seller,
address buyer,
bytes calldata data
) external returns (bool);
function executeBid(
address seller,
address previousBidder,
address bidder,
bytes calldata data
) external returns (bool);
function executeAuctionComplete(
address seller,
address buyer,
bytes calldata data
) external returns (bool);
function executeAuctionRefund(
address seller,
address lastBidder,
bytes calldata data
) external returns (bool);
}contracts/test/x2y2/IWETHUpgradable.sol
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.0;
pragma abicoder v2;
import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol';
interface IWETHUpgradable is IERC20Upgradeable {
function deposit() external payable;
function withdraw(uint256 wad) external;
}contracts/test/x2y2/MarketConsts.sol
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.0;
pragma abicoder v2;
import './IDelegate.sol';
import './IWETHUpgradable.sol';
library Market {
uint256 constant INTENT_SELL = 1;
uint256 constant INTENT_AUCTION = 2;
uint256 constant INTENT_BUY = 3;
uint8 constant SIGN_V1 = 1;
uint8 constant SIGN_V3 = 3;
struct OrderItem {
uint256 price;
bytes data;
}
struct Order {
uint256 salt;
address user;
uint256 network;
uint256 intent;
uint256 delegateType;
uint256 deadline;
IERC20Upgradeable currency;
bytes dataMask;
OrderItem[] items;
// signature
bytes32 r;
bytes32 s;
uint8 v;
uint8 signVersion;
}
struct Fee {
uint256 percentage;
address to;
}
struct SettleDetail {
Market.Op op;
uint256 orderIdx;
uint256 itemIdx;
uint256 price;
bytes32 itemHash;
IDelegate executionDelegate;
bytes dataReplacement;
uint256 bidIncentivePct;
uint256 aucMinIncrementPct;
uint256 aucIncDurationSecs;
Fee[] fees;
}
struct SettleShared {
uint256 salt;
uint256 deadline;
uint256 amountToEth;
uint256 amountToWeth;
address user;
bool canFail;
}
struct RunInput {
Order[] orders;
SettleDetail[] details;
SettleShared shared;
// signature
bytes32 r;
bytes32 s;
uint8 v;
}
struct OngoingAuction {
uint256 price;
uint256 netPrice;
uint256 endAt;
address bidder;
}
enum InvStatus {
NEW,
AUCTION,
COMPLETE,
CANCELLED,
REFUNDED
}
enum Op {
INVALID,
// off-chain
COMPLETE_SELL_OFFER,
COMPLETE_BUY_OFFER,
CANCEL_OFFER,
// auction
BID,
COMPLETE_AUCTION,
REFUND_AUCTION,
REFUND_AUCTION_STUCK_ITEM
}
enum DelegationType {
INVALID,
ERC721,
ERC1155
}
}contracts/test/x2y2/X2Y2Exchange.sol
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.0;
pragma abicoder v2;
import './IDelegate.sol';
import './IWETHUpgradable.sol';
import './MarketConsts.sol';
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import '@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
interface IX2Y2Run {
function run1(
Market.Order memory order,
Market.SettleShared memory shared,
Market.SettleDetail memory detail
) external returns (uint256);
}
contract X2Y2_r1 is
Initializable,
ReentrancyGuardUpgradeable,
OwnableUpgradeable,
PausableUpgradeable,
IX2Y2Run
{
using SafeERC20Upgradeable for IERC20Upgradeable;
event EvProfit(bytes32 itemHash, address currency, address to, uint256 amount);
event EvAuctionRefund(
bytes32 indexed itemHash,
address currency,
address to,
uint256 amount,
uint256 incentive
);
event EvInventory(
bytes32 indexed itemHash,
address maker,
address taker,
uint256 orderSalt,
uint256 settleSalt,
uint256 intent,
uint256 delegateType,
uint256 deadline,
IERC20Upgradeable currency,
bytes dataMask,
Market.OrderItem item,
Market.SettleDetail detail
);
event EvSigner(address signer, bool isRemoval);
event EvDelegate(address delegate, bool isRemoval);
event EvFeeCapUpdate(uint256 newValue);
event EvCancel(bytes32 indexed itemHash);
event EvFailure(uint256 index, bytes error);
mapping(address => bool) public delegates;
mapping(address => bool) public signers;
mapping(bytes32 => Market.InvStatus) public inventoryStatus;
mapping(bytes32 => Market.OngoingAuction) public ongoingAuctions;
uint256 public constant RATE_BASE = 1e6;
uint256 public feeCapPct;
IWETHUpgradable public weth;
receive() external payable {}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function initialize(uint256 feeCapPct_, address weth_) public initializer {
feeCapPct = feeCapPct_;
weth = IWETHUpgradable(weth_);
__ReentrancyGuard_init_unchained();
__Pausable_init_unchained();
__Ownable_init_unchained();
}
function updateFeeCap(uint256 val) public virtual onlyOwner {
feeCapPct = val;
emit EvFeeCapUpdate(val);
}
function updateSigners(address[] memory toAdd, address[] memory toRemove)
public
virtual
onlyOwner
{
for (uint256 i = 0; i < toAdd.length; i++) {
signers[toAdd[i]] = true;
emit EvSigner(toAdd[i], false);
}
for (uint256 i = 0; i < toRemove.length; i++) {
delete signers[toRemove[i]];
emit EvSigner(toRemove[i], true);
}
}
function updateDelegates(address[] memory toAdd, address[] memory toRemove)
public
virtual
onlyOwner
{
for (uint256 i = 0; i < toAdd.length; i++) {
delegates[toAdd[i]] = true;
emit EvDelegate(toAdd[i], false);
}
for (uint256 i = 0; i < toRemove.length; i++) {
delete delegates[toRemove[i]];
emit EvDelegate(toRemove[i], true);
}
}
function cancel(
bytes32[] memory itemHashes,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual nonReentrant whenNotPaused {
require(deadline > block.timestamp, 'deadline reached');
bytes32 hash = keccak256(abi.encode(itemHashes.length, itemHashes, deadline));
address signer = ECDSA.recover(hash, v, r, s);
require(signers[signer], 'Input signature error');
for (uint256 i = 0; i < itemHashes.length; i++) {
bytes32 h = itemHashes[i];
if (inventoryStatus[h] == Market.InvStatus.NEW) {
inventoryStatus[h] = Market.InvStatus.CANCELLED;
emit EvCancel(h);
}
}
}
function run(Market.RunInput memory input) public payable virtual nonReentrant whenNotPaused {
require(input.shared.deadline > block.timestamp, 'input deadline reached');
require(msg.sender == input.shared.user, 'sender does not match');
_verifyInputSignature(input);
uint256 amountEth = msg.value;
if (input.shared.amountToWeth > 0) {
uint256 amt = input.shared.amountToWeth;
weth.deposit{value: amt}();
SafeERC20Upgradeable.safeTransfer(weth, msg.sender, amt);
amountEth -= amt;
}
if (input.shared.amountToEth > 0) {
uint256 amt = input.shared.amountToEth;
SafeERC20Upgradeable.safeTransferFrom(weth, msg.sender, address(this), amt);
weth.withdraw(amt);
amountEth += amt;
}
for (uint256 i = 0; i < input.orders.length; i++) {
_verifyOrderSignature(input.orders[i]);
}
for (uint256 i = 0; i < input.details.length; i++) {
Market.SettleDetail memory detail = input.details[i];
Market.Order memory order = input.orders[detail.orderIdx];
if (input.shared.canFail) {
try IX2Y2Run(address(this)).run1(order, input.shared, detail) returns (
uint256 ethPayment
) {
amountEth -= ethPayment;
} catch Error(string memory _err) {
emit EvFailure(i, bytes(_err));
} catch (bytes memory _err) {
emit EvFailure(i, _err);
}
} else {
amountEth -= _run(order, input.shared, detail);
}
}
if (amountEth > 0) {
payable(msg.sender).transfer(amountEth);
}
}
function run1(
Market.Order memory order,
Market.SettleShared memory shared,
Market.SettleDetail memory detail
) external virtual returns (uint256) {
require(msg.sender == address(this), 'unsafe call');
return _run(order, shared, detail);
}
function _hashItem(Market.Order memory order, Market.OrderItem memory item)
internal
view
virtual
returns (bytes32)
{
return
keccak256(
abi.encode(
order.salt,
order.user,
order.network,
order.intent,
order.delegateType,
order.deadline,
order.currency,
order.dataMask,
item
)
);
}
function _emitInventory(
bytes32 itemHash,
Market.Order memory order,
Market.OrderItem memory item,
Market.SettleShared memory shared,
Market.SettleDetail memory detail
) internal virtual {
emit EvInventory(
itemHash,
order.user,
shared.user,
order.salt,
shared.salt,
order.intent,
order.delegateType,
order.deadline,
order.currency,
order.dataMask,
item,
detail
);
}
function _run(
Market.Order memory order,
Market.SettleShared memory shared,
Market.SettleDetail memory detail
) internal virtual returns (uint256) {
uint256 nativeAmount = 0;
Market.OrderItem memory item = order.items[detail.itemIdx];
bytes32 itemHash = _hashItem(order, item);
{
require(itemHash == detail.itemHash, 'item hash does not match');
require(order.network == block.chainid, 'wrong network');
require(
address(detail.executionDelegate) != address(0) &&
delegates[address(detail.executionDelegate)],
'unknown delegate'
);
}
bytes memory data = item.data;
{
if (order.dataMask.length > 0 && detail.dataReplacement.length > 0) {
_arrayReplace(data, detail.dataReplacement, order.dataMask);
}
}
if (detail.op == Market.Op.COMPLETE_SELL_OFFER) {
require(inventoryStatus[itemHash] == Market.InvStatus.NEW, 'order already exists');
require(order.intent == Market.INTENT_SELL, 'intent != sell');
_assertDelegation(order, detail);
require(order.deadline > block.timestamp, 'deadline reached');
require(detail.price >= item.price, 'underpaid');
nativeAmount = _takePayment(itemHash, order.currency, shared.user, detail.price);
require(
detail.executionDelegate.executeSell(order.user, shared.user, data),
'delegation error'
);
_distributeFeeAndProfit(
itemHash,
order.user,
order.currency,
detail,
detail.price,
detail.price
);
inventoryStatus[itemHash] = Market.InvStatus.COMPLETE;
} else if (detail.op == Market.Op.COMPLETE_BUY_OFFER) {
require(inventoryStatus[itemHash] == Market.InvStatus.NEW, 'order already exists');
require(order.intent == Market.INTENT_BUY, 'intent != buy');
_assertDelegation(order, detail);
require(order.deadline > block.timestamp, 'deadline reached');
require(item.price == detail.price, 'price not match');
require(!_isNative(order.currency), 'native token not supported');
nativeAmount = _takePayment(itemHash, order.currency, order.user, detail.price);
require(
detail.executionDelegate.executeBuy(shared.user, order.user, data),
'delegation error'
);
_distributeFeeAndProfit(
itemHash,
shared.user,
order.currency,
detail,
detail.price,
detail.price
);
inventoryStatus[itemHash] = Market.InvStatus.COMPLETE;
} else if (detail.op == Market.Op.CANCEL_OFFER) {
require(inventoryStatus[itemHash] == Market.InvStatus.NEW, 'unable to cancel');
require(order.deadline > block.timestamp, 'deadline reached');
inventoryStatus[itemHash] = Market.InvStatus.CANCELLED;
emit EvCancel(itemHash);
} else if (detail.op == Market.Op.BID) {
require(order.intent == Market.INTENT_AUCTION, 'intent != auction');
_assertDelegation(order, detail);
bool firstBid = false;
if (ongoingAuctions[itemHash].bidder == address(0)) {
require(inventoryStatus[itemHash] == Market.InvStatus.NEW, 'order already exists');
require(order.deadline > block.timestamp, 'auction ended');
require(detail.price >= item.price, 'underpaid');
firstBid = true;
ongoingAuctions[itemHash] = Market.OngoingAuction({
price: detail.price,
netPrice: detail.price,
bidder: shared.user,
endAt: order.deadline
});
inventoryStatus[itemHash] = Market.InvStatus.AUCTION;
require(
detail.executionDelegate.executeBid(order.user, address(0), shared.user, data),
'delegation error'
);
}
Market.OngoingAuction storage auc = ongoingAuctions[itemHash];
require(auc.endAt > block.timestamp, 'auction ended');
nativeAmount = _takePayment(itemHash, order.currency, shared.user, detail.price);
if (!firstBid) {
require(
inventoryStatus[itemHash] == Market.InvStatus.AUCTION,
'order is not auction'
);
require(
detail.price - auc.price >= (auc.price * detail.aucMinIncrementPct) / RATE_BASE,
'underbid'
);
uint256 bidRefund = auc.netPrice;
uint256 incentive = (detail.price * detail.bidIncentivePct) / RATE_BASE;
if (bidRefund + incentive > 0) {
_transferTo(order.currency, auc.bidder, bidRefund + incentive);
emit EvAuctionRefund(
itemHash,
address(order.currency),
auc.bidder,
bidRefund,
incentive
);
}
require(
detail.executionDelegate.executeBid(order.user, auc.bidder, shared.user, data),
'delegation error'
);
auc.price = detail.price;
auc.netPrice = detail.price - incentive;
auc.bidder = shared.user;
}
if (block.timestamp + detail.aucIncDurationSecs > auc.endAt) {
auc.endAt += detail.aucIncDurationSecs;
}
} else if (
detail.op == Market.Op.REFUND_AUCTION ||
detail.op == Market.Op.REFUND_AUCTION_STUCK_ITEM
) {
require(
inventoryStatus[itemHash] == Market.InvStatus.AUCTION,
'cannot cancel non-auction order'
);
Market.OngoingAuction storage auc = ongoingAuctions[itemHash];
if (auc.netPrice > 0) {
_transferTo(order.currency, auc.bidder, auc.netPrice);
emit EvAuctionRefund(
itemHash,
address(order.currency),
auc.bidder,
auc.netPrice,
0
);
}
_assertDelegation(order, detail);
if (detail.op == Market.Op.REFUND_AUCTION) {
require(
detail.executionDelegate.executeAuctionRefund(order.user, auc.bidder, data),
'delegation error'
);
}
delete ongoingAuctions[itemHash];
inventoryStatus[itemHash] = Market.InvStatus.REFUNDED;
} else if (detail.op == Market.Op.COMPLETE_AUCTION) {
require(
inventoryStatus[itemHash] == Market.InvStatus.AUCTION,
'cannot complete non-auction order'
);
_assertDelegation(order, detail);
Market.OngoingAuction storage auc = ongoingAuctions[itemHash];
require(block.timestamp >= auc.endAt, 'auction not finished yet');
require(
detail.executionDelegate.executeAuctionComplete(order.user, auc.bidder, data),
'delegation error'
);
_distributeFeeAndProfit(
itemHash,
order.user,
order.currency,
detail,
auc.price,
auc.netPrice
);
inventoryStatus[itemHash] = Market.InvStatus.COMPLETE;
delete ongoingAuctions[itemHash];
} else {
revert('unknown op');
}
_emitInventory(itemHash, order, item, shared, detail);
return nativeAmount;
}
function _assertDelegation(Market.Order memory order, Market.SettleDetail memory detail)
internal
view
virtual
{
require(
detail.executionDelegate.delegateType() == order.delegateType,
'delegation type error'
);
}
// modifies `src`
function _arrayReplace(
bytes memory src,
bytes memory replacement,
bytes memory mask
) internal view virtual {
require(src.length == replacement.length);
require(src.length == mask.length);
for (uint256 i = 0; i < src.length; i++) {
if (mask[i] != 0) {
src[i] = replacement[i];
}
}
}
function _verifyInputSignature(Market.RunInput memory input) internal view virtual {
bytes32 hash = keccak256(abi.encode(input.shared, input.details.length, input.details));
address signer = ECDSA.recover(hash, input.v, input.r, input.s);
require(signers[signer], 'Input signature error');
}
function _verifyOrderSignature(Market.Order memory order) internal view virtual {
address orderSigner;
if (order.signVersion == Market.SIGN_V1) {
bytes32 orderHash = keccak256(
abi.encode(
order.salt,
order.user,
order.network,
order.intent,
order.delegateType,
order.deadline,
order.currency,
order.dataMask,
order.items.length,
order.items
)
);
orderSigner = ECDSA.recover(
ECDSA.toEthSignedMessageHash(orderHash),
order.v,
order.r,
order.s
);
} else {
revert('unknown signature version');
}
require(orderSigner == order.user, 'Order signature does not match');
}
function _isNative(IERC20Upgradeable currency) internal view virtual returns (bool) {
return address(currency) == address(0);
}
function _takePayment(
bytes32 itemHash,
IERC20Upgradeable currency,
address from,
uint256 amount
) internal virtual returns (uint256) {
if (amount > 0) {
if (_isNative(currency)) {
return amount;
} else {
currency.safeTransferFrom(from, address(this), amount);
}
}
return 0;
}
function _transferTo(
IERC20Upgradeable currency,
address to,
uint256 amount
) internal virtual {
if (amount > 0) {
if (_isNative(currency)) {
AddressUpgradeable.sendValue(payable(to), amount);
} else {
currency.safeTransfer(to, amount);
}
}
}
function _distributeFeeAndProfit(
bytes32 itemHash,
address seller,
IERC20Upgradeable currency,
Market.SettleDetail memory sd,
uint256 price,
uint256 netPrice
) internal virtual {
require(price >= netPrice, 'price error');
uint256 payment = netPrice;
uint256 totalFeePct;
for (uint256 i = 0; i < sd.fees.length; i++) {
Market.Fee memory fee = sd.fees[i];
totalFeePct += fee.percentage;
uint256 amount = (price * fee.percentage) / RATE_BASE;
payment -= amount;
_transferTo(currency, fee.to, amount);
}
require(feeCapPct >= totalFeePct, 'total fee cap exceeded');
_transferTo(currency, seller, payment);
emit EvProfit(itemHash, address(currency), seller, payment);
}
}Compiler settingsShow
{
"libraries": {},
"optimizer": {
"runs": 1337,
"enabled": true
}
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.