Transaction Hash:
Block:
15376484 at Aug-20-2022 08:08:25 AM +UTC
Transaction Fee:
0.000926909278500725 ETH
$2.00
Gas Used:
127,075 Gas / 7.294190663 Gwei
Emitted Events:
| 152 |
mfers.Approval( owner=0x119e064119ecd5f396dc13258bcfc141df54f7cb, approved=0x00000000...000000000, tokenId=2831 )
|
| 153 |
mfers.Transfer( from=0x119e064119ecd5f396dc13258bcfc141df54f7cb, to=[Sender] 0xe2286cebf12b499c6506f2ce3d45ad695f070356, tokenId=2831 )
|
| 154 |
ElementEx.0x8a0f8e04e7a35efabdc150b7d106308198a4f965a5d11badf768c5b8b273ac94( 0x8a0f8e04e7a35efabdc150b7d106308198a4f965a5d11badf768c5b8b273ac94, 000000000000000000000000119e064119ecd5f396dc13258bcfc141df54f7cb, 000000000000000000000000e2286cebf12b499c6506f2ce3d45ad695f070356, 000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, 0000000000000000000000000000000000000000000000000cc47f20295c0000, 00000000000000000000000079fcdef22feed20eddacbb2587640e45491b757f, 0000000000000000000000000000000000000000000000000000000000000b0f, b6c4e0525f71f2b70d9879c3e45c8756a663b42386ac6160d41a502d40a19a36 )
|
Account State Difference:
| Address | Before | After | State Difference | ||
|---|---|---|---|---|---|
| 0x119E0641...1dF54f7CB | 0.030743451871455429 Eth | 0.950743451871455429 Eth | 0.92 | ||
| 0x20F780A9...2a50a77c4 | (Element: ElementEx) | ||||
| 0x79FCDEF2...5491b757f | |||||
|
0x829BD824...93333A830
Miner
| (F2Pool Old) | 3,179.771736217542191584 Eth | 3,179.771926830042191584 Eth | 0.0001906125 | |
| 0xe2286CEb...95f070356 |
0.981574970606837768 Eth
Nonce: 47
|
0.060648061328337043 Eth
Nonce: 48
| 0.920926909278500725 |
Execution Trace
ETH 0.92
ElementEx.5f57685e( )
ETH 0.92
ERC721OrdersFeature.buyERC721( sellOrder=[{name:maker, type:address, order:1, indexed:false, value:0x119E064119eCD5f396dC13258BcFC141dF54f7CB, valueString:0x119E064119eCD5f396dC13258BcFC141dF54f7CB}, {name:taker, type:address, order:2, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}, {name:expiry, type:uint256, order:3, indexed:false, value:1661069306, valueString:1661069306}, {name:nonce, type:uint256, order:4, indexed:false, value:17, valueString:17}, {name:erc20Token, type:address, order:5, indexed:false, value:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, valueString:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE}, {name:erc20TokenAmount, type:uint256, order:6, indexed:false, value:920000000000000000, valueString:920000000000000000}, {name:fees, type:tuple[], order:7, indexed:false}, {name:nft, type:address, order:8, indexed:false, value:0x79FCDEF22feeD20eDDacbB2587640e45491b757f, valueString:0x79FCDEF22feeD20eDDacbB2587640e45491b757f}, {name:nftId, type:uint256, order:9, indexed:false, value:2831, valueString:2831}], signature=[{name:signatureType, type:uint8, order:1, indexed:false, value:0, valueString:0}, {name:v, type:uint8, order:2, indexed:false, value:28, valueString:28}, {name:r, type:bytes32, order:3, indexed:false, value:E042689044D3FDA832FE4455966B5BE8BEECE439DE5EDE48FBB5833FEB3E48FA, valueString:E042689044D3FDA832FE4455966B5BE8BEECE439DE5EDE48FBB5833FEB3E48FA}, {name:s, type:bytes32, order:4, indexed:false, value:2B154576D1E683C02121CFC74B3F5448BB5AD199DA37A36099974DF870229090, valueString:2B154576D1E683C02121CFC74B3F5448BB5AD199DA37A36099974DF870229090}] )-
Null: 0x000...001.b6c4e052( ) -
mfers.transferFrom( from=0x119E064119eCD5f396dC13258BcFC141dF54f7CB, to=0xe2286CEbF12b499C6506f2CE3d45ad695f070356, tokenId=2831 )
- ETH 0.92
0x119e064119ecd5f396dc13258bcfc141df54f7cb.CALL( )
-
buyERC721[ERC721OrdersFeature (ln:54)]
_buyERC721[ERC721OrdersFeature (ln:56)]_buyNFT[ERC721OrdersFeature (ln:414)]ERC721SellOrderFilled[ERC721OrdersFeature (ln:415)]
_transferEth[ERC721OrdersFeature (ln:59)]payable[ERC721OrdersFeature (ln:59)]
File 1 of 3: ElementEx
File 2 of 3: mfers
File 3 of 3: ERC721OrdersFeature
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "./migrations/LibBootstrap.sol";
import "./features/BootstrapFeature.sol";
import "./storage/LibProxyStorage.sol";
/// @dev An extensible proxy contract that serves as a universal entry point for
/// interacting with the 0x protocol.
contract ElementEx {
/// @dev Construct this contract and register the `BootstrapFeature` feature.
/// After constructing this contract, `bootstrap()` should be called
/// by `bootstrap()` to seed the initial feature set.
/// @param bootstrapper Who can call `bootstrap()`.
constructor(address bootstrapper) {
// Temporarily create and register the bootstrap feature.
// It will deregister itself after `bootstrap()` has been called.
BootstrapFeature bootstrap = new BootstrapFeature(bootstrapper);
LibProxyStorage.getStorage().impls[bootstrap.bootstrap.selector] =
address(bootstrap);
}
// solhint-disable state-visibility
/// @dev Forwards calls to the appropriate implementation contract.
fallback() external payable {
bytes memory b = msg.data;
bytes4 selector;
assembly {
selector := mload(add(b, 32))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
selector := and(selector, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
address impl = LibProxyStorage.getStorage().impls[selector];
if (impl == address(0)) {
revert("METHOD_NOT_IMPLEMENTED");
}
(bool success, bytes memory resultData) = impl.delegatecall(msg.data);
if (!success) {
_revertWithData(resultData);
}
_returnWithData(resultData);
}
/// @dev Fallback for just receiving ether.
receive() external payable {}
// solhint-enable state-visibility
/// @dev Get the implementation contract of a registered function.
/// @param selector The function selector.
/// @return impl The implementation contract address.
function getFunctionImplementation(bytes4 selector) public view returns (address impl) {
return LibProxyStorage.getStorage().impls[selector];
}
/// @dev Revert with arbitrary bytes.
/// @param data Revert data.
function _revertWithData(bytes memory data) private pure {
assembly { revert(add(data, 32), mload(data)) }
}
/// @dev Return with arbitrary bytes.
/// @param data Return data.
function _returnWithData(bytes memory data) private pure {
assembly { return(add(data, 32), mload(data)) }
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
library LibBootstrap {
/// @dev Magic bytes returned by the bootstrapper to indicate success.
/// This is `keccack('BOOTSTRAP_SUCCESS')`.
bytes4 internal constant BOOTSTRAP_SUCCESS = 0xd150751b;
/// @dev Perform a delegatecall and ensure it returns the magic bytes.
/// @param target The call target.
/// @param data The call data.
function delegatecallBootstrapFunction(address target, bytes memory data) internal {
(bool success, bytes memory resultData) = target.delegatecall(data);
if (!success ||
resultData.length != 32 ||
abi.decode(resultData, (bytes4)) != BOOTSTRAP_SUCCESS)
{
revert("BOOTSTRAP_CALL_FAILED");
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "../migrations/LibBootstrap.sol";
import "../storage/LibProxyStorage.sol";
import "./interfaces/IBootstrapFeature.sol";
/// @dev Detachable `bootstrap()` feature.
contract BootstrapFeature is IBootstrapFeature {
// solhint-disable state-visibility,indent
/// @dev The ZeroEx contract.
/// This has to be immutable to persist across delegatecalls.
address immutable private _deployer;
/// @dev The implementation address of this contract.
/// This has to be immutable to persist across delegatecalls.
address immutable private _implementation;
/// @dev The deployer.
/// This has to be immutable to persist across delegatecalls.
address immutable private _bootstrapCaller;
// solhint-enable state-visibility,indent
/// @dev Construct this contract and set the bootstrap migration contract.
/// After constructing this contract, `bootstrap()` should be called
/// to seed the initial feature set.
/// @param bootstrapCaller The allowed caller of `bootstrap()`.
constructor(address bootstrapCaller) {
_deployer = msg.sender;
_implementation = address(this);
_bootstrapCaller = bootstrapCaller;
}
/// @dev Bootstrap the initial feature set of this contract by delegatecalling
/// into `target`. Before exiting the `bootstrap()` function will
/// deregister itself from the proxy to prevent being called again.
/// @param target The bootstrapper contract address.
/// @param callData The call data to execute on `target`.
function bootstrap(address target, bytes calldata callData) external override {
// Only the bootstrap caller can call this function.
if (msg.sender != _bootstrapCaller) {
revert("INVALID_BOOTSTRAP_CALLER");
}
// Deregister.
LibProxyStorage.getStorage().impls[this.bootstrap.selector] = address(0);
// Self-destruct.
BootstrapFeature(_implementation).die();
// Call the bootstrapper.
LibBootstrap.delegatecallBootstrapFunction(target, callData);
}
/// @dev Self-destructs this contract.
/// Can only be called by the deployer.
function die() external {
require(address(this) == _implementation);
if (msg.sender != _deployer) {
revert("INVALID_DIE_CALLER");
}
selfdestruct(payable(msg.sender));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "./LibStorage.sol";
/// @dev Storage helpers for the proxy contract.
library LibProxyStorage {
/// @dev Storage bucket for proxy contract.
struct Storage {
// Mapping of function selector -> function implementation
mapping(bytes4 => address) impls;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.STORAGE_ID_PROXY;
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor.slot := storageSlot }
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
/// @dev Detachable `bootstrap()` feature.
interface IBootstrapFeature {
/// @dev Bootstrap the initial feature set of this contract by delegatecalling
/// into `target`. Before exiting the `bootstrap()` function will
/// deregister itself from the proxy to prevent being called again.
/// @param target The bootstrapper contract address.
/// @param callData The call data to execute on `target`.
function bootstrap(address target, bytes calldata callData) external;
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
/// @dev Common storage helpers
library LibStorage {
/// @dev What to bit-shift a storage ID by to get its slot.
/// This gives us a maximum of 2**128 inline fields in each bucket.
uint256 constant STORAGE_ID_PROXY = 1 << 128;
uint256 constant STORAGE_ID_SIMPLE_FUNCTION_REGISTRY = 2 << 128;
uint256 constant STORAGE_ID_OWNABLE = 3 << 128;
uint256 constant STORAGE_ID_COMMON_NFT_ORDERS = 4 << 128;
uint256 constant STORAGE_ID_ERC721_ORDERS = 5 << 128;
uint256 constant STORAGE_ID_ERC1155_ORDERS = 6 << 128;
}
File 2 of 3: mfers
// SPDX-License-Identifier: MIT
/*
__
_ __ ___ / _| ___ _ __ ___
| '_ ` _ \\ | |_ / _ \\ | '__| / __|
| | | | | | | _| | __/ | | \\__ \\
|_| |_| |_| |_| \\___| |_| |___/
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
contract mfers is ERC721, ERC721Enumerable, Ownable {
string public PROVENANCE;
bool public saleIsActive = false;
string private _baseURIextended;
address payable public immutable shareholderAddress;
constructor(address payable shareholderAddress_) ERC721("mfer", "MFER") {
require(shareholderAddress_ != address(0));
shareholderAddress = shareholderAddress_;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
function setBaseURI(string memory baseURI_) external onlyOwner() {
_baseURIextended = baseURI_;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
function setProvenance(string memory provenance) public onlyOwner {
PROVENANCE = provenance;
}
function reserve() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 150; i++) {
_safeMint(msg.sender, supply + i);
}
}
function setSaleState(bool newState) public onlyOwner {
saleIsActive = newState;
}
function mint(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Tokens");
require(numberOfTokens <= 10, "Exceeded max token purchase");
require(totalSupply() + numberOfTokens <= 10021, "Purchase would exceed max supply of tokens");
require(0.069 ether * numberOfTokens <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < 10021) {
_safeMint(msg.sender, mintIndex);
}
}
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
Address.sendValue(shareholderAddress, balance);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @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.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
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() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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 {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
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`, 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 be 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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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 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);
/**
* @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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 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);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
File 3 of 3: ERC721OrdersFeature
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "../../fixins/FixinERC721Spender.sol";
import "../../storage/LibCommonNftOrdersStorage.sol";
import "../../storage/LibERC721OrdersStorage.sol";
import "../interfaces/IERC721OrdersFeature.sol";
import "./NFTOrders.sol";
/// @dev Feature for interacting with ERC721 orders.
contract ERC721OrdersFeature is IERC721OrdersFeature, FixinERC721Spender, NFTOrders {
using LibNFTOrder for LibNFTOrder.NFTBuyOrder;
/// @dev The magic return value indicating the success of a `onERC721Received`.
bytes4 private constant ERC721_RECEIVED_MAGIC_BYTES = this.onERC721Received.selector;
constructor(IEtherToken weth) NFTOrders(weth) {
}
/// @dev Sells an ERC721 asset to fill the given order.
/// @param buyOrder The ERC721 buy order.
/// @param signature The order signature from the maker.
/// @param erc721TokenId The ID of the ERC721 asset being
/// sold. If the given order specifies properties,
/// the asset must satisfy those properties. Otherwise,
/// it must equal the tokenId in the order.
/// @param unwrapNativeToken If this parameter is true and the
/// ERC20 token of the order is e.g. WETH, unwraps the
/// token before transferring it to the taker.
/// @param callbackData If this parameter is non-zero, invokes
/// `zeroExERC721OrderCallback` on `msg.sender` after
/// the ERC20 tokens have been transferred to `msg.sender`
/// but before transferring the ERC721 asset to the buyer.
function sellERC721(
LibNFTOrder.NFTBuyOrder memory buyOrder,
LibSignature.Signature memory signature,
uint256 erc721TokenId,
bool unwrapNativeToken,
bytes memory callbackData
) public override {
_sellERC721(buyOrder, signature, erc721TokenId, unwrapNativeToken, msg.sender, msg.sender, callbackData);
}
/// @dev Buys an ERC721 asset by filling the given order.
/// @param sellOrder The ERC721 sell order.
/// @param signature The order signature.
function buyERC721(LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature) public override payable {
uint256 ethBalanceBefore = address(this).balance - msg.value;
_buyERC721(sellOrder, signature);
if (address(this).balance != ethBalanceBefore) {
// Refund
_transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore);
}
}
function buyERC721Ex(
LibNFTOrder.NFTSellOrder memory sellOrder,
LibSignature.Signature memory signature,
address taker,
bytes memory callbackData
) public override payable {
uint256 ethBalanceBefore = address(this).balance - msg.value;
_buyERC721Ex(sellOrder, signature, taker, msg.value, callbackData);
if (address(this).balance != ethBalanceBefore) {
// Refund
_transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore);
}
}
/// @dev Cancel a single ERC721 order by its nonce. The caller
/// should be the maker of the order. Silently succeeds if
/// an order with the same nonce has already been filled or
/// cancelled.
/// @param orderNonce The order nonce.
function cancelERC721Order(uint256 orderNonce) public override {
// Mark order as cancelled
_setOrderStatusBit(msg.sender, orderNonce);
emit ERC721OrderCancelled(msg.sender, orderNonce);
}
/// @dev Cancel multiple ERC721 orders by their nonces. The caller
/// should be the maker of the orders. Silently succeeds if
/// an order with the same nonce has already been filled or
/// cancelled.
/// @param orderNonces The order nonces.
function batchCancelERC721Orders(uint256[] calldata orderNonces) external override {
for (uint256 i = 0; i < orderNonces.length; i++) {
cancelERC721Order(orderNonces[i]);
}
}
/// @dev Buys multiple ERC721 assets by filling the
/// given orders.
/// @param sellOrders The ERC721 sell orders.
/// @param signatures The order signatures.
/// @param revertIfIncomplete If true, reverts if this
/// function fails to fill any individual order.
/// @return successes An array of booleans corresponding to whether
/// each order in `orders` was successfully filled.
function batchBuyERC721s(
LibNFTOrder.NFTSellOrder[] memory sellOrders,
LibSignature.Signature[] memory signatures,
bool revertIfIncomplete
) public override payable returns (bool[] memory successes) {
// Array length must match.
uint256 length = sellOrders.length;
require(length == signatures.length, "ARRAY_LENGTH_MISMATCH");
successes = new bool[](length);
uint256 ethBalanceBefore = address(this).balance - msg.value;
if (revertIfIncomplete) {
for (uint256 i = 0; i < length; i++) {
// Will revert if _buyERC721 reverts.
_buyERC721(sellOrders[i], signatures[i]);
successes[i] = true;
}
} else {
for (uint256 i = 0; i < length; i++) {
// Delegatecall `buyERC721FromProxy` to swallow reverts while
// preserving execution context.
(successes[i], ) = _implementation.delegatecall(
abi.encodeWithSelector(this.buyERC721FromProxy.selector, sellOrders[i], signatures[i])
);
}
}
// Refund
_transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore);
}
function batchBuyERC721sEx(
LibNFTOrder.NFTSellOrder[] memory sellOrders,
LibSignature.Signature[] memory signatures,
address[] calldata takers,
bytes[] memory callbackData,
bool revertIfIncomplete
) public override payable returns (bool[] memory successes) {
// All array length must match.
uint256 length = sellOrders.length;
require(length == signatures.length && length == takers.length && length == callbackData.length, "ARRAY_LENGTH_MISMATCH");
successes = new bool[](length);
uint256 ethBalanceBefore = address(this).balance - msg.value;
if (revertIfIncomplete) {
for (uint256 i = 0; i < length; i++) {
// Will revert if _buyERC721Ex reverts.
_buyERC721Ex(sellOrders[i], signatures[i], takers[i], address(this).balance - ethBalanceBefore, callbackData[i]);
successes[i] = true;
}
} else {
for (uint256 i = 0; i < length; i++) {
// Delegatecall `buyERC721ExFromProxy` to swallow reverts while
// preserving execution context.
(successes[i], ) = _implementation.delegatecall(
abi.encodeWithSelector(this.buyERC721ExFromProxy.selector, sellOrders[i], signatures[i], takers[i],
address(this).balance - ethBalanceBefore, callbackData[i])
);
}
}
// Refund
_transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore);
}
// @Note `buyERC721FromProxy` is a external function, must call from an external Exchange Proxy,
// but should not be registered in the Exchange Proxy.
function buyERC721FromProxy(LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature) external payable {
require(_implementation != address(this), "MUST_CALL_FROM_PROXY");
_buyERC721(sellOrder, signature);
}
// @Note `buyERC721ExFromProxy` is a external function, must call from an external Exchange Proxy,
// but should not be registered in the Exchange Proxy.
function buyERC721ExFromProxy(LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, address taker, uint256 ethAvailable, bytes memory takerCallbackData) external payable {
require(_implementation != address(this), "MUST_CALL_FROM_PROXY");
_buyERC721Ex(sellOrder, signature, taker, ethAvailable, takerCallbackData);
}
/// @dev Matches a pair of complementary orders that have
/// a non-negative spread. Each order is filled at
/// their respective price, and the matcher receives
/// a profit denominated in the ERC20 token.
/// @param sellOrder Order selling an ERC721 asset.
/// @param buyOrder Order buying an ERC721 asset.
/// @param sellOrderSignature Signature for the sell order.
/// @param buyOrderSignature Signature for the buy order.
/// @return profit The amount of profit earned by the caller
/// of this function (denominated in the ERC20 token
/// of the matched orders).
function matchERC721Orders(
LibNFTOrder.NFTSellOrder memory sellOrder,
LibNFTOrder.NFTBuyOrder memory buyOrder,
LibSignature.Signature memory sellOrderSignature,
LibSignature.Signature memory buyOrderSignature
) public override returns (uint256 profit) {
// The ERC721 tokens must match
require(sellOrder.nft == buyOrder.nft, "ERC721_TOKEN_MISMATCH_ERROR");
LibNFTOrder.OrderInfo memory sellOrderInfo = _getOrderInfo(sellOrder);
LibNFTOrder.OrderInfo memory buyOrderInfo = _getOrderInfo(buyOrder);
_validateSellOrder(sellOrder, sellOrderSignature, sellOrderInfo, buyOrder.maker);
_validateBuyOrder(buyOrder, buyOrderSignature, buyOrderInfo, sellOrder.maker, sellOrder.nftId);
// English Auction
if (sellOrder.expiry >> 252 == 2) {
_resetEnglishAuctionTokenAmountAndFees(sellOrder, buyOrder.erc20TokenAmount, 1, 1);
}
// Mark both orders as filled.
_updateOrderState(sellOrder, sellOrderInfo.orderHash, 1);
_updateOrderState(buyOrder.asNFTSellOrder(), buyOrderInfo.orderHash, 1);
// The difference in ERC20 token amounts is the spread.
uint256 spread = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount;
// Transfer the ERC721 asset from seller to buyer.
_transferERC721AssetFrom(sellOrder.nft, sellOrder.maker, buyOrder.maker, sellOrder.nftId);
// Handle the ERC20 side of the order:
if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS && buyOrder.erc20Token == WETH) {
// The sell order specifies ETH, while the buy order specifies WETH.
// The orders are still compatible with one another, but we'll have
// to unwrap the WETH on behalf of the buyer.
// Step 1: Transfer WETH from the buyer to the EP.
// Note that we transfer `buyOrder.erc20TokenAmount`, which
// is the amount the buyer signaled they are willing to pay
// for the ERC721 asset, which may be more than the seller's
// ask.
_transferERC20TokensFrom(WETH, buyOrder.maker, address(this), buyOrder.erc20TokenAmount);
// Step 2: Unwrap the WETH into ETH. We unwrap the entire
// `buyOrder.erc20TokenAmount`.
// The ETH will be used for three purposes:
// - To pay the seller
// - To pay fees for the sell order
// - Any remaining ETH will be sent to
// `msg.sender` as profit.
WETH.withdraw(buyOrder.erc20TokenAmount);
// Step 3: Pay the seller (in ETH).
_transferEth(payable(sellOrder.maker), sellOrder.erc20TokenAmount);
// Step 4: Pay fees for the buy order. Note that these are paid
// in _WETH_ by the _buyer_. By signing the buy order, the
// buyer signals that they are willing to spend a total
// of `erc20TokenAmount` _plus_ fees, all denominated in
// the `erc20Token`, which in this case is WETH.
_payFees(buyOrder.asNFTSellOrder(), buyOrder.maker, 1, 1, false);
// Step 5: Pay fees for the sell order. The `erc20Token` of the
// sell order is ETH, so the fees are paid out in ETH.
// There should be `spread` wei of ETH remaining in the
// EP at this point, which we will use ETH to pay the
// sell order fees.
uint256 sellOrderFees = _payFees(sellOrder, address(this), 1, 1, true);
// Step 6: The spread less the sell order fees is the amount of ETH
// remaining in the EP that can be sent to `msg.sender` as
// the profit from matching these two orders.
profit = spread - sellOrderFees;
if (profit > 0) {
_transferEth(payable(msg.sender), profit);
}
} else {
// ERC20 tokens must match
require(sellOrder.erc20Token == buyOrder.erc20Token, "ERC20_TOKEN_MISMATCH_ERROR");
// Step 1: Transfer the ERC20 token from the buyer to the seller.
// Note that we transfer `sellOrder.erc20TokenAmount`, which
// is at most `buyOrder.erc20TokenAmount`.
_transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, sellOrder.maker, sellOrder.erc20TokenAmount);
// Step 2: Pay fees for the buy order. Note that these are paid
// by the buyer. By signing the buy order, the buyer signals
// that they are willing to spend a total of
// `buyOrder.erc20TokenAmount` _plus_ `buyOrder.fees`.
_payFees(buyOrder.asNFTSellOrder(), buyOrder.maker, 1, 1, false);
// Step 3: Pay fees for the sell order. These are paid by the buyer
// as well. After paying these fees, we may have taken more
// from the buyer than they agreed to in the buy order. If
// so, we revert in the following step.
uint256 sellOrderFees = _payFees(sellOrder, buyOrder.maker, 1, 1, false);
// Step 4: We calculate the profit as:
// profit = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount - sellOrderFees
// = spread - sellOrderFees
// I.e. the buyer would've been willing to pay up to `profit`
// more to buy the asset, so instead that amount is sent to
// `msg.sender` as the profit from matching these two orders.
profit = spread - sellOrderFees;
if (profit > 0) {
_transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, msg.sender, profit);
}
}
emit ERC721SellOrderFilled(
sellOrder.maker,
buyOrder.maker, // taker
sellOrder.erc20Token,
sellOrder.erc20TokenAmount,
sellOrder.nft,
sellOrder.nftId,
sellOrderInfo.orderHash
);
emit ERC721BuyOrderFilled(
buyOrder.maker,
sellOrder.maker, // taker
buyOrder.erc20Token,
buyOrder.erc20TokenAmount,
buyOrder.nft,
sellOrder.nftId,
buyOrderInfo.orderHash
);
}
/// @dev Matches pairs of complementary orders that have
/// non-negative spreads. Each order is filled at
/// their respective price, and the matcher receives
/// a profit denominated in the ERC20 token.
/// @param sellOrders Orders selling ERC721 assets.
/// @param buyOrders Orders buying ERC721 assets.
/// @param sellOrderSignatures Signatures for the sell orders.
/// @param buyOrderSignatures Signatures for the buy orders.
/// @return profits The amount of profit earned by the caller
/// of this function for each pair of matched orders
/// (denominated in the ERC20 token of the order pair).
/// @return successes An array of booleans corresponding to
/// whether each pair of orders was successfully matched.
function batchMatchERC721Orders(
LibNFTOrder.NFTSellOrder[] memory sellOrders,
LibNFTOrder.NFTBuyOrder[] memory buyOrders,
LibSignature.Signature[] memory sellOrderSignatures,
LibSignature.Signature[] memory buyOrderSignatures
) public override returns (uint256[] memory profits, bool[] memory successes) {
// All array length must match.
uint256 length = sellOrders.length;
require(length == buyOrders.length && length == sellOrderSignatures.length && length == buyOrderSignatures.length, "ARRAY_LENGTH_MISMATCH");
profits = new uint256[](length);
successes = new bool[](length);
for (uint256 i = 0; i < length; i++) {
bytes memory returnData;
// Delegatecall `matchERC721Orders` to catch reverts while
// preserving execution context.
(successes[i], returnData) = _implementation.delegatecall(
abi.encodeWithSelector(this.matchERC721Orders.selector, sellOrders[i], buyOrders[i],
sellOrderSignatures[i], buyOrderSignatures[i])
);
if (successes[i]) {
// If the matching succeeded, record the profit.
(uint256 profit) = abi.decode(returnData, (uint256));
profits[i] = profit;
}
}
}
/// @dev Callback for the ERC721 `safeTransferFrom` function.
/// This callback can be used to sell an ERC721 asset if
/// a valid ERC721 order, signature and `unwrapNativeToken`
/// are encoded in `data`. This allows takers to sell their
/// ERC721 asset without first calling `setApprovalForAll`.
/// @param operator The address which called `safeTransferFrom`.
/// @param tokenId The ID of the asset being transferred.
/// @param data Additional data with no specified format. If a
/// valid ERC721 order, signature and `unwrapNativeToken`
/// are encoded in `data`, this function will try to fill
/// the order using the received asset.
/// @return success The selector of this function (0x150b7a02),
/// indicating that the callback succeeded.
function onERC721Received(address operator, address /* from */, uint256 tokenId, bytes calldata data) external override returns (bytes4 success) {
// Decode the order, signature, and `unwrapNativeToken` from
// `data`. If `data` does not encode such parameters, this
// will throw.
(LibNFTOrder.NFTBuyOrder memory buyOrder, LibSignature.Signature memory signature, bool unwrapNativeToken)
= abi.decode(data, (LibNFTOrder.NFTBuyOrder, LibSignature.Signature, bool));
// `onERC721Received` is called by the ERC721 token contract.
// Check that it matches the ERC721 token in the order.
require(msg.sender == buyOrder.nft, "ERC721_TOKEN_MISMATCH_ERROR");
// operator taker
// address(this) owner (we hold the NFT currently)
_sellERC721(buyOrder, signature, tokenId, unwrapNativeToken, operator, address(this), new bytes(0));
return ERC721_RECEIVED_MAGIC_BYTES;
}
/// @dev Approves an ERC721 sell order on-chain. After pre-signing
/// the order, the `PRESIGNED` signature type will become
/// valid for that order and signer.
/// @param order An ERC721 sell order.
function preSignERC721SellOrder(LibNFTOrder.NFTSellOrder memory order) public override {
require(order.maker == msg.sender, "ONLY_MAKER");
uint256 hashNonce = LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker];
bytes32 orderHash = getERC721SellOrderHash(order);
LibERC721OrdersStorage.getStorage().preSigned[orderHash] = (hashNonce + 1);
emit ERC721SellOrderPreSigned(order.maker, order.taker, order.expiry, order.nonce,
order.erc20Token, order.erc20TokenAmount, order.fees, order.nft, order.nftId);
}
/// @dev Approves an ERC721 buy order on-chain. After pre-signing
/// the order, the `PRESIGNED` signature type will become
/// valid for that order and signer.
/// @param order An ERC721 buy order.
function preSignERC721BuyOrder(LibNFTOrder.NFTBuyOrder memory order) public override {
require(order.maker == msg.sender, "ONLY_MAKER");
uint256 hashNonce = LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker];
bytes32 orderHash = getERC721BuyOrderHash(order);
LibERC721OrdersStorage.getStorage().preSigned[orderHash] = (hashNonce + 1);
emit ERC721BuyOrderPreSigned(order.maker, order.taker, order.expiry, order.nonce,
order.erc20Token, order.erc20TokenAmount, order.fees, order.nft, order.nftId, order.nftProperties);
}
// Core settlement logic for selling an ERC721 asset.
// Used by `sellERC721` and `onERC721Received`.
function _sellERC721(
LibNFTOrder.NFTBuyOrder memory buyOrder,
LibSignature.Signature memory signature,
uint256 erc721TokenId,
bool unwrapNativeToken,
address taker,
address currentNftOwner,
bytes memory takerCallbackData
) private {
(, bytes32 orderHash) = _sellNFT(
buyOrder,
signature,
SellParams(1, erc721TokenId, unwrapNativeToken, taker, currentNftOwner, takerCallbackData)
);
emit ERC721BuyOrderFilled(
buyOrder.maker,
taker,
buyOrder.erc20Token,
buyOrder.erc20TokenAmount,
buyOrder.nft,
erc721TokenId,
orderHash
);
}
// Core settlement logic for buying an ERC721 asset.
// Used by `buyERC721` and `batchBuyERC721s`.
function _buyERC721(LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature) internal {
(, bytes32 orderHash) = _buyNFT(sellOrder, signature, 1);
emit ERC721SellOrderFilled(
sellOrder.maker,
msg.sender,
sellOrder.erc20Token,
sellOrder.erc20TokenAmount,
sellOrder.nft,
sellOrder.nftId,
orderHash
);
}
function _buyERC721Ex(
LibNFTOrder.NFTSellOrder memory sellOrder,
LibSignature.Signature memory signature,
address taker,
uint256 ethAvailable,
bytes memory takerCallbackData
) internal {
if (taker == address (0)) {
taker = msg.sender;
} else {
require(taker != address(this), "_buy721Ex/TAKER_CANNOT_SELF");
}
(, bytes32 orderHash) = _buyNFTEx(sellOrder, signature, BuyParams(1, ethAvailable, taker, takerCallbackData));
emit ERC721SellOrderFilled(
sellOrder.maker,
taker,
sellOrder.erc20Token,
sellOrder.erc20TokenAmount,
sellOrder.nft,
sellOrder.nftId,
orderHash
);
}
/// @dev Checks whether the given signature is valid for the
/// the given ERC721 sell order. Reverts if not.
/// @param order The ERC721 sell order.
/// @param signature The signature to validate.
function validateERC721SellOrderSignature(LibNFTOrder.NFTSellOrder memory order, LibSignature.Signature memory signature) public override view {
_validateOrderSignature(getERC721SellOrderHash(order), signature, order.maker);
}
/// @dev Checks whether the given signature is valid for the
/// the given ERC721 buy order. Reverts if not.
/// @param order The ERC721 buy order.
/// @param signature The signature to validate.
function validateERC721BuyOrderSignature(LibNFTOrder.NFTBuyOrder memory order, LibSignature.Signature memory signature) public override view {
_validateOrderSignature(getERC721BuyOrderHash(order), signature, order.maker);
}
/// @dev Validates that the given signature is valid for the
/// given maker and order hash. Reverts if the signature
/// is not valid.
/// @param orderHash The hash of the order that was signed.
/// @param signature The signature to check.
/// @param maker The maker of the order.
function _validateOrderSignature(bytes32 orderHash, LibSignature.Signature memory signature, address maker) internal override view {
if (signature.signatureType == LibSignature.SignatureType.PRESIGNED) {
require(LibERC721OrdersStorage.getStorage().preSigned[orderHash]
== LibCommonNftOrdersStorage.getStorage().hashNonces[maker] + 1, "PRESIGNED_INVALID_SIGNER");
} else {
require(maker != address(0) && maker == ecrecover(orderHash, signature.v, signature.r, signature.s), "INVALID_SIGNER_ERROR");
}
}
/// @dev Transfers an NFT asset.
/// @param token The address of the NFT contract.
/// @param from The address currently holding the asset.
/// @param to The address to transfer the asset to.
/// @param tokenId The ID of the asset to transfer.
function _transferNFTAssetFrom(address token, address from, address to, uint256 tokenId, uint256 /* amount */) internal override {
_transferERC721AssetFrom(token, from, to, tokenId);
}
/// @dev Updates storage to indicate that the given order
/// has been filled by the given amount.
/// @param order The order that has been filled.
function _updateOrderState(LibNFTOrder.NFTSellOrder memory order, bytes32 /* orderHash */, uint128 /* fillAmount */) internal override {
_setOrderStatusBit(order.maker, order.nonce);
}
function _setOrderStatusBit(address maker, uint256 nonce) private {
// The bitvector is indexed by the lower 8 bits of the nonce.
uint256 flag = 1 << (nonce & 255);
// Update order status bit vector to indicate that the given order
// has been cancelled/filled by setting the designated bit to 1.
LibERC721OrdersStorage.getStorage().orderStatusByMaker[maker][uint248(nonce >> 8)] |= flag;
}
/// @dev Get the current status of an ERC721 sell order.
/// @param order The ERC721 sell order.
/// @return status The status of the order.
function getERC721SellOrderStatus(LibNFTOrder.NFTSellOrder memory order) public override view returns (LibNFTOrder.OrderStatus) {
// Check for listingTime.
// Gas Optimize, listingTime only used in rare cases.
if (order.expiry & 0xffffffff00000000 > 0) {
if ((order.expiry >> 32) & 0xffffffff > block.timestamp) {
return LibNFTOrder.OrderStatus.INVALID;
}
}
// Check for expiryTime.
if (order.expiry & 0xffffffff <= block.timestamp) {
return LibNFTOrder.OrderStatus.EXPIRED;
}
// Check `orderStatusByMaker` state variable to see if the order
// has been cancelled or previously filled.
LibERC721OrdersStorage.Storage storage stor = LibERC721OrdersStorage.getStorage();
// `orderStatusByMaker` is indexed by maker and nonce.
uint256 orderStatusBitVector = stor.orderStatusByMaker[order.maker][uint248(order.nonce >> 8)];
// The bitvector is indexed by the lower 8 bits of the nonce.
uint256 flag = 1 << (order.nonce & 255);
// If the designated bit is set, the order has been cancelled or
// previously filled, so it is now unfillable.
if (orderStatusBitVector & flag != 0) {
return LibNFTOrder.OrderStatus.UNFILLABLE;
}
// Otherwise, the order is fillable.
return LibNFTOrder.OrderStatus.FILLABLE;
}
/// @dev Get the current status of an ERC721 buy order.
/// @param order The ERC721 buy order.
/// @return status The status of the order.
function getERC721BuyOrderStatus(LibNFTOrder.NFTBuyOrder memory order) public override view returns (LibNFTOrder.OrderStatus) {
// Only buy orders with `nftId` == 0 can be property orders.
if (order.nftId != 0 && order.nftProperties.length > 0) {
return LibNFTOrder.OrderStatus.INVALID;
}
// Buy orders cannot use ETH as the ERC20 token, since ETH cannot be
// transferred from the buyer by a contract.
if (address(order.erc20Token) == NATIVE_TOKEN_ADDRESS) {
return LibNFTOrder.OrderStatus.INVALID;
}
return getERC721SellOrderStatus(order.asNFTSellOrder());
}
/// @dev Get the order info for an NFT sell order.
/// @param nftSellOrder The NFT sell order.
/// @return orderInfo Info about the order.
function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal override view returns (LibNFTOrder.OrderInfo memory) {
LibNFTOrder.OrderInfo memory orderInfo;
orderInfo.orderHash = getERC721SellOrderHash(nftSellOrder);
orderInfo.status = getERC721SellOrderStatus(nftSellOrder);
orderInfo.orderAmount = 1;
orderInfo.remainingAmount = orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE ? 1 : 0;
return orderInfo;
}
/// @dev Get the order info for an NFT buy order.
/// @param nftBuyOrder The NFT buy order.
/// @return orderInfo Info about the order.
function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal override view returns (LibNFTOrder.OrderInfo memory) {
LibNFTOrder.OrderInfo memory orderInfo;
orderInfo.orderHash = getERC721BuyOrderHash(nftBuyOrder);
orderInfo.status = getERC721BuyOrderStatus(nftBuyOrder);
orderInfo.orderAmount = 1;
orderInfo.remainingAmount = orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE ? 1 : 0;
return orderInfo;
}
/// @dev Get the EIP-712 hash of an ERC721 sell order.
/// @param order The ERC721 sell order.
/// @return orderHash The order hash.
function getERC721SellOrderHash(LibNFTOrder.NFTSellOrder memory order) public override view returns (bytes32) {
return _getEIP712Hash(LibNFTOrder.getNFTSellOrderStructHash(
order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker]));
}
/// @dev Get the EIP-712 hash of an ERC721 buy order.
/// @param order The ERC721 buy order.
/// @return orderHash The order hash.
function getERC721BuyOrderHash(LibNFTOrder.NFTBuyOrder memory order) public override view returns (bytes32) {
return _getEIP712Hash(LibNFTOrder.getNFTBuyOrderStructHash(
order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker]));
}
/// @dev Get the order status bit vector for the given
/// maker address and nonce range.
/// @param maker The maker of the order.
/// @param nonceRange Order status bit vectors are indexed
/// by maker address and the upper 248 bits of the
/// order nonce. We define `nonceRange` to be these
/// 248 bits.
/// @return bitVector The order status bit vector for the
/// given maker and nonce range.
function getERC721OrderStatusBitVector(address maker, uint248 nonceRange) external override view returns (uint256) {
return LibERC721OrdersStorage.getStorage().orderStatusByMaker[maker][nonceRange];
}
function getHashNonce(address maker) external override view returns (uint256) {
return LibCommonNftOrdersStorage.getStorage().hashNonces[maker];
}
/// Increment a particular maker's nonce, thereby invalidating all orders that were not signed
/// with the original nonce.
function incrementHashNonce() external override {
uint256 newHashNonce = ++LibCommonNftOrdersStorage.getStorage().hashNonces[msg.sender];
emit HashNonceIncremented(msg.sender, newHashNonce);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
/// @dev Helpers for moving ERC721 assets around.
abstract contract FixinERC721Spender {
// Mask of the lower 20 bytes of a bytes32.
uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
/// @dev Transfers an ERC721 asset from `owner` to `to`.
/// @param token The address of the ERC721 token contract.
/// @param owner The owner of the asset.
/// @param to The recipient of the asset.
/// @param tokenId The token ID of the asset to transfer.
function _transferERC721AssetFrom(address token, address owner, address to, uint256 tokenId) internal {
uint256 success;
assembly {
let ptr := mload(0x40) // free memory pointer
// selector for transferFrom(address,address,uint256)
mstore(ptr, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK))
mstore(add(ptr, 0x24), and(to, ADDRESS_MASK))
mstore(add(ptr, 0x44), tokenId)
success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, 0, 0)
}
require(success != 0, "_transferERC721/TRANSFER_FAILED");
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 Element.Market
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "./LibStorage.sol";
library LibCommonNftOrdersStorage {
/// @dev Storage bucket for this feature.
struct Storage {
/* Track per-maker nonces that can be incremented by the maker to cancel orders in bulk. */
// The current nonce for the maker represents the only valid nonce that can be signed by the maker
// If a signature was signed with a nonce that's different from the one stored in nonces, it
// will fail validation.
mapping(address => uint256) hashNonces;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.STORAGE_ID_COMMON_NFT_ORDERS;
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor.slot := storageSlot }
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "./LibStorage.sol";
/// @dev Storage helpers for `ERC721OrdersFeature`.
library LibERC721OrdersStorage {
/// @dev Storage bucket for this feature.
struct Storage {
// maker => nonce range => order status bit vector
mapping(address => mapping(uint248 => uint256)) orderStatusByMaker;
// order hash => hashNonce
mapping(bytes32 => uint256) preSigned;
}
/// @dev Get the storage bucket for this contract.
function getStorage() internal pure returns (Storage storage stor) {
uint256 storageSlot = LibStorage.STORAGE_ID_ERC721_ORDERS;
// Dip into assembly to change the slot pointed to by the local
// variable `stor`.
// See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries
assembly { stor.slot := storageSlot }
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../libs/LibNFTOrder.sol";
import "../libs/LibSignature.sol";
/// @dev Feature for interacting with ERC721 orders.
interface IERC721OrdersFeature {
/// @dev Emitted whenever an `ERC721SellOrder` is filled.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param erc20Token The address of the ERC20 token.
/// @param erc20TokenAmount The amount of ERC20 token to sell.
/// @param erc721Token The address of the ERC721 token.
/// @param erc721TokenId The ID of the ERC721 asset.
/// @param orderHash The `ERC721SellOrder` hash.
event ERC721SellOrderFilled(
address maker,
address taker,
IERC20 erc20Token,
uint256 erc20TokenAmount,
address erc721Token,
uint256 erc721TokenId,
bytes32 orderHash
);
/// @dev Emitted whenever an `ERC721BuyOrder` is filled.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param erc20Token The address of the ERC20 token.
/// @param erc20TokenAmount The amount of ERC20 token to buy.
/// @param erc721Token The address of the ERC721 token.
/// @param erc721TokenId The ID of the ERC721 asset.
/// @param orderHash The `ERC721BuyOrder` hash.
event ERC721BuyOrderFilled(
address maker,
address taker,
IERC20 erc20Token,
uint256 erc20TokenAmount,
address erc721Token,
uint256 erc721TokenId,
bytes32 orderHash
);
/// @dev Emitted when an `ERC721SellOrder` is pre-signed.
/// Contains all the fields of the order.
event ERC721SellOrderPreSigned(
address maker,
address taker,
uint256 expiry,
uint256 nonce,
IERC20 erc20Token,
uint256 erc20TokenAmount,
LibNFTOrder.Fee[] fees,
address erc721Token,
uint256 erc721TokenId
);
/// @dev Emitted when an `ERC721BuyOrder` is pre-signed.
/// Contains all the fields of the order.
event ERC721BuyOrderPreSigned(
address maker,
address taker,
uint256 expiry,
uint256 nonce,
IERC20 erc20Token,
uint256 erc20TokenAmount,
LibNFTOrder.Fee[] fees,
address erc721Token,
uint256 erc721TokenId,
LibNFTOrder.Property[] nftProperties
);
/// @dev Emitted whenever an `ERC721Order` is cancelled.
/// @param maker The maker of the order.
/// @param nonce The nonce of the order that was cancelled.
event ERC721OrderCancelled(address maker, uint256 nonce);
/// @dev Emitted HashNonceIncremented.
event HashNonceIncremented(address maker, uint256 newHashNonce);
/// @dev Sells an ERC721 asset to fill the given order.
/// @param buyOrder The ERC721 buy order.
/// @param signature The order signature from the maker.
/// @param erc721TokenId The ID of the ERC721 asset being
/// sold. If the given order specifies properties,
/// the asset must satisfy those properties. Otherwise,
/// it must equal the tokenId in the order.
/// @param unwrapNativeToken If this parameter is true and the
/// ERC20 token of the order is e.g. WETH, unwraps the
/// token before transferring it to the taker.
/// @param callbackData If this parameter is non-zero, invokes
/// `zeroExERC721OrderCallback` on `msg.sender` after
/// the ERC20 tokens have been transferred to `msg.sender`
/// but before transferring the ERC721 asset to the buyer.
function sellERC721(LibNFTOrder.NFTBuyOrder calldata buyOrder, LibSignature.Signature calldata signature, uint256 erc721TokenId, bool unwrapNativeToken, bytes calldata callbackData) external;
/// @dev Buys an ERC721 asset by filling the given order.
/// @param sellOrder The ERC721 sell order.
/// @param signature The order signature.
function buyERC721(LibNFTOrder.NFTSellOrder calldata sellOrder, LibSignature.Signature calldata signature) external payable;
/// @dev Buys an ERC721 asset by filling the given order.
/// @param sellOrder The ERC721 sell order.
/// @param signature The order signature.
/// @param taker The address to receive ERC721. If this parameter
/// is zero, transfer ERC721 to `msg.sender`.
/// @param callbackData If this parameter is non-zero, invokes
/// `zeroExERC721OrderCallback` on `msg.sender` after
/// the ERC721 asset has been transferred to `msg.sender`
/// but before transferring the ERC20 tokens to the seller.
/// Native tokens acquired during the callback can be used
/// to fill the order.
function buyERC721Ex(LibNFTOrder.NFTSellOrder calldata sellOrder, LibSignature.Signature calldata signature, address taker, bytes calldata callbackData) external payable;
/// @dev Cancel a single ERC721 order by its nonce. The caller
/// should be the maker of the order. Silently succeeds if
/// an order with the same nonce has already been filled or
/// cancelled.
/// @param orderNonce The order nonce.
function cancelERC721Order(uint256 orderNonce) external;
/// @dev Cancel multiple ERC721 orders by their nonces. The caller
/// should be the maker of the orders. Silently succeeds if
/// an order with the same nonce has already been filled or
/// cancelled.
/// @param orderNonces The order nonces.
function batchCancelERC721Orders(uint256[] calldata orderNonces) external;
/// @dev Buys multiple ERC721 assets by filling the
/// given orders.
/// @param sellOrders The ERC721 sell orders.
/// @param signatures The order signatures.
/// @param revertIfIncomplete If true, reverts if this
/// function fails to fill any individual order.
/// @return successes An array of booleans corresponding to whether
/// each order in `orders` was successfully filled.
function batchBuyERC721s(
LibNFTOrder.NFTSellOrder[] calldata sellOrders,
LibSignature.Signature[] calldata signatures,
bool revertIfIncomplete
) external payable returns (bool[] memory successes);
/// @dev Buys multiple ERC721 assets by filling the
/// given orders.
/// @param sellOrders The ERC721 sell orders.
/// @param signatures The order signatures.
/// @param takers The address to receive ERC721.
/// @param callbackData The data (if any) to pass to the taker
/// callback for each order. Refer to the `callbackData`
/// parameter to for `buyERC721`.
/// @param revertIfIncomplete If true, reverts if this
/// function fails to fill any individual order.
/// @return successes An array of booleans corresponding to whether
/// each order in `orders` was successfully filled.
function batchBuyERC721sEx(
LibNFTOrder.NFTSellOrder[] calldata sellOrders,
LibSignature.Signature[] calldata signatures,
address[] calldata takers,
bytes[] calldata callbackData,
bool revertIfIncomplete
) external payable returns (bool[] memory successes);
/// @dev Matches a pair of complementary orders that have
/// a non-negative spread. Each order is filled at
/// their respective price, and the matcher receives
/// a profit denominated in the ERC20 token.
/// @param sellOrder Order selling an ERC721 asset.
/// @param buyOrder Order buying an ERC721 asset.
/// @param sellOrderSignature Signature for the sell order.
/// @param buyOrderSignature Signature for the buy order.
/// @return profit The amount of profit earned by the caller
/// of this function (denominated in the ERC20 token
/// of the matched orders).
function matchERC721Orders(
LibNFTOrder.NFTSellOrder calldata sellOrder,
LibNFTOrder.NFTBuyOrder calldata buyOrder,
LibSignature.Signature calldata sellOrderSignature,
LibSignature.Signature calldata buyOrderSignature
) external returns (uint256 profit);
/// @dev Matches pairs of complementary orders that have
/// non-negative spreads. Each order is filled at
/// their respective price, and the matcher receives
/// a profit denominated in the ERC20 token.
/// @param sellOrders Orders selling ERC721 assets.
/// @param buyOrders Orders buying ERC721 assets.
/// @param sellOrderSignatures Signatures for the sell orders.
/// @param buyOrderSignatures Signatures for the buy orders.
/// @return profits The amount of profit earned by the caller
/// of this function for each pair of matched orders
/// (denominated in the ERC20 token of the order pair).
/// @return successes An array of booleans corresponding to
/// whether each pair of orders was successfully matched.
function batchMatchERC721Orders(
LibNFTOrder.NFTSellOrder[] calldata sellOrders,
LibNFTOrder.NFTBuyOrder[] calldata buyOrders,
LibSignature.Signature[] calldata sellOrderSignatures,
LibSignature.Signature[] calldata buyOrderSignatures
) external returns (uint256[] memory profits, bool[] memory successes);
/// @dev Callback for the ERC721 `safeTransferFrom` function.
/// This callback can be used to sell an ERC721 asset if
/// a valid ERC721 order, signature and `unwrapNativeToken`
/// are encoded in `data`. This allows takers to sell their
/// ERC721 asset without first calling `setApprovalForAll`.
/// @param operator The address which called `safeTransferFrom`.
/// @param from The address which previously owned the token.
/// @param tokenId The ID of the asset being transferred.
/// @param data Additional data with no specified format. If a
/// valid ERC721 order, signature and `unwrapNativeToken`
/// are encoded in `data`, this function will try to fill
/// the order using the received asset.
/// @return success The selector of this function (0x150b7a02),
/// indicating that the callback succeeded.
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4 success);
/// @dev Approves an ERC721 sell order on-chain. After pre-signing
/// the order, the `PRESIGNED` signature type will become
/// valid for that order and signer.
/// @param order An ERC721 sell order.
function preSignERC721SellOrder(LibNFTOrder.NFTSellOrder calldata order) external;
/// @dev Approves an ERC721 buy order on-chain. After pre-signing
/// the order, the `PRESIGNED` signature type will become
/// valid for that order and signer.
/// @param order An ERC721 buy order.
function preSignERC721BuyOrder(LibNFTOrder.NFTBuyOrder calldata order) external;
/// @dev Checks whether the given signature is valid for the
/// the given ERC721 sell order. Reverts if not.
/// @param order The ERC721 sell order.
/// @param signature The signature to validate.
function validateERC721SellOrderSignature(LibNFTOrder.NFTSellOrder calldata order, LibSignature.Signature calldata signature) external view;
/// @dev Checks whether the given signature is valid for the
/// the given ERC721 buy order. Reverts if not.
/// @param order The ERC721 buy order.
/// @param signature The signature to validate.
function validateERC721BuyOrderSignature(LibNFTOrder.NFTBuyOrder calldata order, LibSignature.Signature calldata signature) external view;
/// @dev Get the current status of an ERC721 sell order.
/// @param order The ERC721 sell order.
/// @return status The status of the order.
function getERC721SellOrderStatus(LibNFTOrder.NFTSellOrder calldata order) external view returns (LibNFTOrder.OrderStatus);
/// @dev Get the current status of an ERC721 buy order.
/// @param order The ERC721 buy order.
/// @return status The status of the order.
function getERC721BuyOrderStatus(LibNFTOrder.NFTBuyOrder calldata order) external view returns (LibNFTOrder.OrderStatus);
/// @dev Get the EIP-712 hash of an ERC721 sell order.
/// @param order The ERC721 sell order.
/// @return orderHash The order hash.
function getERC721SellOrderHash(LibNFTOrder.NFTSellOrder calldata order) external view returns (bytes32);
/// @dev Get the EIP-712 hash of an ERC721 buy order.
/// @param order The ERC721 buy order.
/// @return orderHash The order hash.
function getERC721BuyOrderHash(LibNFTOrder.NFTBuyOrder calldata order) external view returns (bytes32);
/// @dev Get the order status bit vector for the given
/// maker address and nonce range.
/// @param maker The maker of the order.
/// @param nonceRange Order status bit vectors are indexed
/// by maker address and the upper 248 bits of the
/// order nonce. We define `nonceRange` to be these
/// 248 bits.
/// @return bitVector The order status bit vector for the
/// given maker and nonce range.
function getERC721OrderStatusBitVector(address maker, uint248 nonceRange) external view returns (uint256);
function getHashNonce(address maker) external view returns (uint256);
/// Increment a particular maker's nonce, thereby invalidating all orders that were not signed
/// with the original nonce.
function incrementHashNonce() external;
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../fixins/FixinEIP712.sol";
import "../../fixins/FixinTokenSpender.sol";
import "../../vendor/IEtherToken.sol";
import "../../vendor/IFeeRecipient.sol";
import "../../vendor/ITakerCallback.sol";
import "../libs/LibSignature.sol";
import "../libs/LibNFTOrder.sol";
/// @dev Abstract base contract inherited by ERC721OrdersFeature and NFTOrders
abstract contract NFTOrders is FixinEIP712, FixinTokenSpender {
using LibNFTOrder for LibNFTOrder.NFTBuyOrder;
/// @dev Native token pseudo-address.
address constant internal NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev The WETH token contract.
IEtherToken internal immutable WETH;
/// @dev The implementation address of this feature.
address internal immutable _implementation;
/// @dev The magic return value indicating the success of a `receiveZeroExFeeCallback`.
bytes4 private constant FEE_CALLBACK_MAGIC_BYTES = IFeeRecipient.receiveZeroExFeeCallback.selector;
/// @dev The magic return value indicating the success of a `zeroExTakerCallback`.
bytes4 private constant TAKER_CALLBACK_MAGIC_BYTES = ITakerCallback.zeroExTakerCallback.selector;
constructor(IEtherToken weth) {
require(address(weth) != address(0), "WETH_ADDRESS_ERROR");
WETH = weth;
// Remember this feature's original address.
_implementation = address(this);
}
struct SellParams {
uint128 sellAmount;
uint256 tokenId;
bool unwrapNativeToken;
address taker;
address currentNftOwner;
bytes takerCallbackData;
}
struct BuyParams {
uint128 buyAmount;
uint256 ethAvailable;
address taker;
bytes takerCallbackData;
}
// Core settlement logic for selling an NFT asset.
function _sellNFT(
LibNFTOrder.NFTBuyOrder memory buyOrder,
LibSignature.Signature memory signature,
SellParams memory params
) internal returns (uint256 erc20FillAmount, bytes32 orderHash) {
LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(buyOrder);
orderHash = orderInfo.orderHash;
// Check that the order can be filled.
_validateBuyOrder(buyOrder, signature, orderInfo, params.taker, params.tokenId);
// Check amount.
if (params.sellAmount > orderInfo.remainingAmount) {
revert("_sellNFT/EXCEEDS_REMAINING_AMOUNT");
}
// Update the order state.
_updateOrderState(buyOrder.asNFTSellOrder(), orderInfo.orderHash, params.sellAmount);
// Calculate erc20 pay amount.
erc20FillAmount = (params.sellAmount == orderInfo.orderAmount) ?
buyOrder.erc20TokenAmount : buyOrder.erc20TokenAmount * params.sellAmount / orderInfo.orderAmount;
if (params.unwrapNativeToken) {
// The ERC20 token must be WETH for it to be unwrapped.
require(buyOrder.erc20Token == WETH, "_sellNFT/ERC20_TOKEN_MISMATCH_ERROR");
// Transfer the WETH from the maker to the Exchange Proxy
// so we can unwrap it before sending it to the seller.
// TODO: Probably safe to just use WETH.transferFrom for some
// small gas savings
_transferERC20TokensFrom(WETH, buyOrder.maker, address(this), erc20FillAmount);
// Unwrap WETH into ETH.
WETH.withdraw(erc20FillAmount);
// Send ETH to the seller.
_transferEth(payable(params.taker), erc20FillAmount);
} else {
// Transfer the ERC20 token from the buyer to the seller.
_transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, params.taker, erc20FillAmount);
}
if (params.takerCallbackData.length > 0) {
require(params.taker != address(this), "_sellNFT/CANNOT_CALLBACK_SELF");
// Invoke the callback
bytes4 callbackResult = ITakerCallback(params.taker).zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData);
// Check for the magic success bytes
require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "_sellNFT/CALLBACK_FAILED");
}
// Transfer the NFT asset to the buyer.
// If this function is called from the
// `onNFTReceived` callback the Exchange Proxy
// holds the asset. Otherwise, transfer it from
// the seller.
_transferNFTAssetFrom(buyOrder.nft, params.currentNftOwner, buyOrder.maker, params.tokenId, params.sellAmount);
// The buyer pays the order fees.
_payFees(buyOrder.asNFTSellOrder(), buyOrder.maker, params.sellAmount, orderInfo.orderAmount, false);
}
// Core settlement logic for buying an NFT asset.
function _buyNFT(
LibNFTOrder.NFTSellOrder memory sellOrder,
LibSignature.Signature memory signature,
uint128 buyAmount
) internal returns (uint256 erc20FillAmount, bytes32 orderHash) {
LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder);
orderHash = orderInfo.orderHash;
// Check that the order can be filled.
_validateSellOrder(sellOrder, signature, orderInfo, msg.sender);
// Check amount.
if (buyAmount > orderInfo.remainingAmount) {
revert("_buyNFT/EXCEEDS_REMAINING_AMOUNT");
}
// Update the order state.
_updateOrderState(sellOrder, orderInfo.orderHash, buyAmount);
// Calculate erc20 pay amount.
erc20FillAmount = (buyAmount == orderInfo.orderAmount) ?
sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * buyAmount, orderInfo.orderAmount);
// Transfer the NFT asset to the buyer (`msg.sender`).
_transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, msg.sender, sellOrder.nftId, buyAmount);
if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) {
// Transfer ETH to the seller.
_transferEth(payable(sellOrder.maker), erc20FillAmount);
// Fees are paid from the EP's current balance of ETH.
_payFees(sellOrder, address(this), buyAmount, orderInfo.orderAmount, true);
} else {
// Transfer ERC20 token from the buyer to the seller.
_transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount);
// The buyer pays fees.
_payFees(sellOrder, msg.sender, buyAmount, orderInfo.orderAmount, false);
}
}
function _buyNFTEx(
LibNFTOrder.NFTSellOrder memory sellOrder,
LibSignature.Signature memory signature,
BuyParams memory params
) internal returns (uint256 erc20FillAmount, bytes32 orderHash) {
LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder);
orderHash = orderInfo.orderHash;
// Check that the order can be filled.
_validateSellOrder(sellOrder, signature, orderInfo, params.taker);
// Check amount.
if (params.buyAmount > orderInfo.remainingAmount) {
revert("_buyNFTEx/EXCEEDS_REMAINING_AMOUNT");
}
// Update the order state.
_updateOrderState(sellOrder, orderInfo.orderHash, params.buyAmount);
// Dutch Auction
if (sellOrder.expiry >> 252 == 1) {
uint256 count = (sellOrder.expiry >> 64) & 0xffffffff;
if (count > 0) {
_resetDutchAuctionTokenAmountAndFees(sellOrder, count);
}
}
// Calculate erc20 pay amount.
erc20FillAmount = (params.buyAmount == orderInfo.orderAmount) ?
sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * params.buyAmount, orderInfo.orderAmount);
// Transfer the NFT asset to the buyer.
_transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, params.taker, sellOrder.nftId, params.buyAmount);
uint256 ethAvailable = params.ethAvailable;
if (params.takerCallbackData.length > 0) {
require(params.taker != address(this), "_buyNFTEx/CANNOT_CALLBACK_SELF");
uint256 ethBalanceBeforeCallback = address(this).balance;
// Invoke the callback
bytes4 callbackResult = ITakerCallback(params.taker).zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData);
// Update `ethAvailable` with amount acquired during
// the callback
ethAvailable += address(this).balance - ethBalanceBeforeCallback;
// Check for the magic success bytes
require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "_buyNFTEx/CALLBACK_FAILED");
}
if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) {
uint256 totalPaid = erc20FillAmount + _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount);
if (ethAvailable < totalPaid) {
// Transfer WETH from the buyer to this contract.
uint256 withDrawAmount = totalPaid - ethAvailable;
_transferERC20TokensFrom(WETH, msg.sender, address(this), withDrawAmount);
// Unwrap WETH into ETH.
WETH.withdraw(withDrawAmount);
}
// Transfer ETH to the seller.
_transferEth(payable(sellOrder.maker), erc20FillAmount);
// Fees are paid from the EP's current balance of ETH.
_payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true);
} else if (sellOrder.erc20Token == WETH) {
uint256 totalFeesPaid = _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount);
if (ethAvailable > totalFeesPaid) {
uint256 depositAmount = ethAvailable - totalFeesPaid;
if (depositAmount < erc20FillAmount) {
// Transfer WETH from the buyer to this contract.
_transferERC20TokensFrom(WETH, msg.sender, address(this), (erc20FillAmount - depositAmount));
} else {
depositAmount = erc20FillAmount;
}
// Wrap ETH.
WETH.deposit{value: depositAmount}();
// Transfer WETH to the seller.
_transferERC20Tokens(WETH, sellOrder.maker, erc20FillAmount);
// Fees are paid from the EP's current balance of ETH.
_payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true);
} else {
// Transfer WETH from the buyer to the seller.
_transferERC20TokensFrom(WETH, msg.sender, sellOrder.maker, erc20FillAmount);
if (ethAvailable > 0) {
if (ethAvailable < totalFeesPaid) {
// Transfer WETH from the buyer to this contract.
uint256 value = totalFeesPaid - ethAvailable;
_transferERC20TokensFrom(WETH, msg.sender, address(this), value);
// Unwrap WETH into ETH.
WETH.withdraw(value);
}
// Fees are paid from the EP's current balance of ETH.
_payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true);
} else {
// The buyer pays fees using WETH.
_payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false);
}
}
} else {
// Transfer ERC20 token from the buyer to the seller.
_transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount);
// The buyer pays fees.
_payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false);
}
}
function _validateSellOrder(
LibNFTOrder.NFTSellOrder memory sellOrder,
LibSignature.Signature memory signature,
LibNFTOrder.OrderInfo memory orderInfo,
address taker
) internal view {
// Taker must match the order taker, if one is specified.
require(sellOrder.taker == address(0) || sellOrder.taker == taker, "_validateOrder/ONLY_TAKER");
// Check that the order is valid and has not expired, been cancelled,
// or been filled.
require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL");
// Check the signature.
_validateOrderSignature(orderInfo.orderHash, signature, sellOrder.maker);
}
function _validateBuyOrder(
LibNFTOrder.NFTBuyOrder memory buyOrder,
LibSignature.Signature memory signature,
LibNFTOrder.OrderInfo memory orderInfo,
address taker,
uint256 tokenId
) internal view {
// The ERC20 token cannot be ETH.
require(address(buyOrder.erc20Token) != NATIVE_TOKEN_ADDRESS, "_validateBuyOrder/TOKEN_MISMATCH");
// Taker must match the order taker, if one is specified.
require(buyOrder.taker == address(0) || buyOrder.taker == taker, "_validateBuyOrder/ONLY_TAKER");
// Check that the order is valid and has not expired, been cancelled,
// or been filled.
require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL");
// Check that the asset with the given token ID satisfies the properties
// specified by the order.
_validateOrderProperties(buyOrder, tokenId);
// Check the signature.
_validateOrderSignature(orderInfo.orderHash, signature, buyOrder.maker);
}
function _resetDutchAuctionTokenAmountAndFees(LibNFTOrder.NFTSellOrder memory order, uint256 count) internal view {
require(count <= 100000000, "COUNT_OUT_OF_SIDE");
uint256 listingTime = (order.expiry >> 32) & 0xffffffff;
uint256 denominator = ((order.expiry & 0xffffffff) - listingTime) * 100000000;
uint256 multiplier = (block.timestamp - listingTime) * count;
// Reset erc20TokenAmount
uint256 amount = order.erc20TokenAmount;
order.erc20TokenAmount = amount - amount * multiplier / denominator;
// Reset fees
for (uint256 i = 0; i < order.fees.length; i++) {
amount = order.fees[i].amount;
order.fees[i].amount = amount - amount * multiplier / denominator;
}
}
function _resetEnglishAuctionTokenAmountAndFees(
LibNFTOrder.NFTSellOrder memory sellOrder,
uint256 buyERC20Amount,
uint256 fillAmount,
uint256 orderAmount
) internal pure {
uint256 sellOrderFees = _calcTotalFeesPaid(sellOrder.fees, fillAmount, orderAmount);
uint256 sellTotalAmount = sellOrderFees + sellOrder.erc20TokenAmount;
if (buyERC20Amount != sellTotalAmount) {
uint256 spread = buyERC20Amount - sellTotalAmount;
uint256 sum;
// Reset fees
if (sellTotalAmount > 0) {
for (uint256 i = 0; i < sellOrder.fees.length; i++) {
uint256 diff = spread * sellOrder.fees[i].amount / sellTotalAmount;
sellOrder.fees[i].amount += diff;
sum += diff;
}
}
// Reset erc20TokenAmount
sellOrder.erc20TokenAmount += spread - sum;
}
}
function _ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// ceil(a / b) = floor((a + b - 1) / b)
return (a + b - 1) / b;
}
function _calcTotalFeesPaid(LibNFTOrder.Fee[] memory fees, uint256 fillAmount, uint256 orderAmount) private pure returns (uint256 totalFeesPaid) {
if (fillAmount == orderAmount) {
for (uint256 i = 0; i < fees.length; i++) {
totalFeesPaid += fees[i].amount;
}
} else {
for (uint256 i = 0; i < fees.length; i++) {
totalFeesPaid += fees[i].amount * fillAmount / orderAmount;
}
}
return totalFeesPaid;
}
function _payFees(
LibNFTOrder.NFTSellOrder memory order,
address payer,
uint128 fillAmount,
uint128 orderAmount,
bool useNativeToken
) internal returns (uint256 totalFeesPaid) {
for (uint256 i = 0; i < order.fees.length; i++) {
LibNFTOrder.Fee memory fee = order.fees[i];
uint256 feeFillAmount = (fillAmount == orderAmount) ? fee.amount : fee.amount * fillAmount / orderAmount;
if (useNativeToken) {
// Transfer ETH to the fee recipient.
_transferEth(payable(fee.recipient), feeFillAmount);
} else {
if (feeFillAmount > 0) {
// Transfer ERC20 token from payer to recipient.
_transferERC20TokensFrom(order.erc20Token, payer, fee.recipient, feeFillAmount);
}
}
// Note that the fee callback is _not_ called if zero
// `feeData` is provided. If `feeData` is provided, we assume
// the fee recipient is a contract that implements the
// `IFeeRecipient` interface.
if (fee.feeData.length > 0) {
// Invoke the callback
bytes4 callbackResult = IFeeRecipient(fee.recipient).receiveZeroExFeeCallback(
useNativeToken ? NATIVE_TOKEN_ADDRESS : address(order.erc20Token),
feeFillAmount,
fee.feeData
);
// Check for the magic success bytes
require(callbackResult == FEE_CALLBACK_MAGIC_BYTES, "_payFees/CALLBACK_FAILED");
}
// Sum the fees paid
totalFeesPaid += feeFillAmount;
}
return totalFeesPaid;
}
function _validateOrderProperties(LibNFTOrder.NFTBuyOrder memory order, uint256 tokenId) internal view {
// If no properties are specified, check that the given
// `tokenId` matches the one specified in the order.
if (order.nftProperties.length == 0) {
require(tokenId == order.nftId, "_validateProperties/TOKEN_ID_ERR");
} else {
// Validate each property
for (uint256 i = 0; i < order.nftProperties.length; i++) {
LibNFTOrder.Property memory property = order.nftProperties[i];
// `address(0)` is interpreted as a no-op. Any token ID
// will satisfy a property with `propertyValidator == address(0)`.
if (address(property.propertyValidator) != address(0)) {
// Call the property validator and throw a descriptive error
// if the call reverts.
try property.propertyValidator.validateProperty(order.nft, tokenId, property.propertyData) {
} catch (bytes memory /* reason */) {
revert("PROPERTY_VALIDATION_FAILED");
}
}
}
}
}
/// @dev Validates that the given signature is valid for the
/// given maker and order hash. Reverts if the signature
/// is not valid.
/// @param orderHash The hash of the order that was signed.
/// @param signature The signature to check.
/// @param maker The maker of the order.
function _validateOrderSignature(bytes32 orderHash, LibSignature.Signature memory signature, address maker) internal virtual view;
/// @dev Transfers an NFT asset.
/// @param token The address of the NFT contract.
/// @param from The address currently holding the asset.
/// @param to The address to transfer the asset to.
/// @param tokenId The ID of the asset to transfer.
/// @param amount The amount of the asset to transfer. Always
/// 1 for ERC721 assets.
function _transferNFTAssetFrom(address token, address from, address to, uint256 tokenId, uint256 amount) internal virtual;
/// @dev Updates storage to indicate that the given order
/// has been filled by the given amount.
/// @param order The order that has been filled.
/// @param orderHash The hash of `order`.
/// @param fillAmount The amount (denominated in the NFT asset)
/// that the order has been filled by.
function _updateOrderState(LibNFTOrder.NFTSellOrder memory order, bytes32 orderHash, uint128 fillAmount) internal virtual;
/// @dev Get the order info for an NFT sell order.
/// @param nftSellOrder The NFT sell order.
/// @return orderInfo Info about the order.
function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory);
/// @dev Get the order info for an NFT buy order.
/// @param nftBuyOrder The NFT buy order.
/// @return orderInfo Info about the order.
function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory);
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
/// @dev Common storage helpers
library LibStorage {
/// @dev What to bit-shift a storage ID by to get its slot.
/// This gives us a maximum of 2**128 inline fields in each bucket.
uint256 constant STORAGE_ID_PROXY = 1 << 128;
uint256 constant STORAGE_ID_SIMPLE_FUNCTION_REGISTRY = 2 << 128;
uint256 constant STORAGE_ID_OWNABLE = 3 << 128;
uint256 constant STORAGE_ID_COMMON_NFT_ORDERS = 4 << 128;
uint256 constant STORAGE_ID_ERC721_ORDERS = 5 << 128;
uint256 constant STORAGE_ID_ERC1155_ORDERS = 6 << 128;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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);
/**
* @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);
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../vendor/IPropertyValidator.sol";
/// @dev A library for common NFT order operations.
library LibNFTOrder {
enum OrderStatus {
INVALID,
FILLABLE,
UNFILLABLE,
EXPIRED
}
struct Property {
IPropertyValidator propertyValidator;
bytes propertyData;
}
struct Fee {
address recipient;
uint256 amount;
bytes feeData;
}
struct NFTSellOrder {
address maker;
address taker;
uint256 expiry;
uint256 nonce;
IERC20 erc20Token;
uint256 erc20TokenAmount;
Fee[] fees;
address nft;
uint256 nftId;
}
// All fields except `nftProperties` align
// with those of NFTSellOrder
struct NFTBuyOrder {
address maker;
address taker;
uint256 expiry;
uint256 nonce;
IERC20 erc20Token;
uint256 erc20TokenAmount;
Fee[] fees;
address nft;
uint256 nftId;
Property[] nftProperties;
}
// All fields except `erc1155TokenAmount` align
// with those of NFTSellOrder
struct ERC1155SellOrder {
address maker;
address taker;
uint256 expiry;
uint256 nonce;
IERC20 erc20Token;
uint256 erc20TokenAmount;
Fee[] fees;
address erc1155Token;
uint256 erc1155TokenId;
// End of fields shared with NFTOrder
uint128 erc1155TokenAmount;
}
// All fields except `erc1155TokenAmount` align
// with those of NFTBuyOrder
struct ERC1155BuyOrder {
address maker;
address taker;
uint256 expiry;
uint256 nonce;
IERC20 erc20Token;
uint256 erc20TokenAmount;
Fee[] fees;
address erc1155Token;
uint256 erc1155TokenId;
Property[] erc1155TokenProperties;
// End of fields shared with NFTOrder
uint128 erc1155TokenAmount;
}
struct OrderInfo {
bytes32 orderHash;
OrderStatus status;
// `orderAmount` is 1 for all ERC721Orders, and
// `erc1155TokenAmount` for ERC1155Orders.
uint128 orderAmount;
// The remaining amount of the ERC721/ERC1155 asset
// that can be filled for the order.
uint128 remainingAmount;
}
// The type hash for sell orders, which is:
// keccak256(abi.encodePacked(
// "NFTSellOrder(",
// "address maker,",
// "address taker,",
// "uint256 expiry,",
// "uint256 nonce,",
// "address erc20Token,",
// "uint256 erc20TokenAmount,",
// "Fee[] fees,",
// "address nft,",
// "uint256 nftId,",
// "uint256 hashNonce",
// ")",
// "Fee(",
// "address recipient,",
// "uint256 amount,",
// "bytes feeData",
// ")"
// ))
uint256 private constant _NFT_SELL_ORDER_TYPE_HASH = 0xed676c7f3e8232a311454799b1cf26e75b4abc90c9bf06c9f7e8e79fcc7fe14d;
// The type hash for buy orders, which is:
// keccak256(abi.encodePacked(
// "NFTBuyOrder(",
// "address maker,",
// "address taker,",
// "uint256 expiry,",
// "uint256 nonce,",
// "address erc20Token,",
// "uint256 erc20TokenAmount,",
// "Fee[] fees,",
// "address nft,",
// "uint256 nftId,",
// "Property[] nftProperties,",
// "uint256 hashNonce",
// ")",
// "Fee(",
// "address recipient,",
// "uint256 amount,",
// "bytes feeData",
// ")",
// "Property(",
// "address propertyValidator,",
// "bytes propertyData",
// ")"
// ))
uint256 private constant _NFT_BUY_ORDER_TYPE_HASH = 0xa525d336300f566329800fcbe82fd263226dc27d6c109f060d9a4a364281521c;
// The type hash for ERC1155 sell orders, which is:
// keccak256(abi.encodePacked(
// "ERC1155SellOrder(",
// "address maker,",
// "address taker,",
// "uint256 expiry,",
// "uint256 nonce,",
// "address erc20Token,",
// "uint256 erc20TokenAmount,",
// "Fee[] fees,",
// "address erc1155Token,",
// "uint256 erc1155TokenId,",
// "uint128 erc1155TokenAmount,",
// "uint256 hashNonce",
// ")",
// "Fee(",
// "address recipient,",
// "uint256 amount,",
// "bytes feeData",
// ")"
// ))
uint256 private constant _ERC_1155_SELL_ORDER_TYPE_HASH = 0x3529b5920cc48ecbceb24e9c51dccb50fefd8db2cf05d36e356aeb1754e19eda;
// The type hash for ERC1155 buy orders, which is:
// keccak256(abi.encodePacked(
// "ERC1155BuyOrder(",
// "address maker,",
// "address taker,",
// "uint256 expiry,",
// "uint256 nonce,",
// "address erc20Token,",
// "uint256 erc20TokenAmount,",
// "Fee[] fees,",
// "address erc1155Token,",
// "uint256 erc1155TokenId,",
// "Property[] erc1155TokenProperties,",
// "uint128 erc1155TokenAmount,",
// "uint256 hashNonce",
// ")",
// "Fee(",
// "address recipient,",
// "uint256 amount,",
// "bytes feeData",
// ")",
// "Property(",
// "address propertyValidator,",
// "bytes propertyData",
// ")"
// ))
uint256 private constant _ERC_1155_BUY_ORDER_TYPE_HASH = 0x1a6eaae1fbed341e0974212ec17f035a9d419cadc3bf5154841cbf7fd605ba48;
// keccak256(abi.encodePacked(
// "Fee(",
// "address recipient,",
// "uint256 amount,",
// "bytes feeData",
// ")"
// ))
uint256 private constant _FEE_TYPE_HASH = 0xe68c29f1b4e8cce0bbcac76eb1334bdc1dc1f293a517c90e9e532340e1e94115;
// keccak256(abi.encodePacked(
// "Property(",
// "address propertyValidator,",
// "bytes propertyData",
// ")"
// ))
uint256 private constant _PROPERTY_TYPE_HASH = 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8;
// keccak256("");
bytes32 private constant _EMPTY_ARRAY_KECCAK256 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// keccak256(abi.encodePacked(keccak256(abi.encode(
// _PROPERTY_TYPE_HASH,
// address(0),
// keccak256("")
// ))));
bytes32 private constant _NULL_PROPERTY_STRUCT_HASH = 0x720ee400a9024f6a49768142c339bf09d2dd9056ab52d20fbe7165faba6e142d;
uint256 private constant ADDRESS_MASK = (1 << 160) - 1;
function asNFTSellOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (NFTSellOrder memory order) {
assembly { order := nftBuyOrder }
}
function asNFTSellOrder(ERC1155SellOrder memory erc1155SellOrder) internal pure returns (NFTSellOrder memory order) {
assembly { order := erc1155SellOrder }
}
function asNFTBuyOrder(ERC1155BuyOrder memory erc1155BuyOrder) internal pure returns (NFTBuyOrder memory order) {
assembly { order := erc1155BuyOrder }
}
function asERC1155SellOrder(NFTSellOrder memory nftSellOrder) internal pure returns (ERC1155SellOrder memory order) {
assembly { order := nftSellOrder }
}
function asERC1155BuyOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (ERC1155BuyOrder memory order) {
assembly { order := nftBuyOrder }
}
// @dev Get the struct hash of an sell order.
/// @param order The sell order.
/// @return structHash The struct hash of the order.
function getNFTSellOrderStructHash(NFTSellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) {
bytes32 feesHash = _feesHash(order.fees);
// Hash in place, equivalent to:
// return keccak256(abi.encode(
// _NFT_SELL_ORDER_TYPE_HASH,
// order.maker,
// order.taker,
// order.expiry,
// order.nonce,
// order.erc20Token,
// order.erc20TokenAmount,
// feesHash,
// order.nft,
// order.nftId,
// hashNonce
// ));
assembly {
if lt(order, 32) { invalid() } // Don't underflow memory.
let typeHashPos := sub(order, 32) // order - 32
let feesHashPos := add(order, 192) // order + (32 * 6)
let hashNoncePos := add(order, 288) // order + (32 * 9)
let typeHashMemBefore := mload(typeHashPos)
let feeHashMemBefore := mload(feesHashPos)
let hashNonceMemBefore := mload(hashNoncePos)
mstore(typeHashPos, _NFT_SELL_ORDER_TYPE_HASH)
mstore(feesHashPos, feesHash)
mstore(hashNoncePos, hashNonce)
structHash := keccak256(typeHashPos, 352 /* 32 * 11 */ )
mstore(typeHashPos, typeHashMemBefore)
mstore(feesHashPos, feeHashMemBefore)
mstore(hashNoncePos, hashNonceMemBefore)
}
return structHash;
}
/// @dev Get the struct hash of an buy order.
/// @param order The buy order.
/// @return structHash The struct hash of the order.
function getNFTBuyOrderStructHash(NFTBuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) {
bytes32 propertiesHash = _propertiesHash(order.nftProperties);
bytes32 feesHash = _feesHash(order.fees);
// Hash in place, equivalent to:
// return keccak256(abi.encode(
// _NFT_BUY_ORDER_TYPE_HASH,
// order.maker,
// order.taker,
// order.expiry,
// order.nonce,
// order.erc20Token,
// order.erc20TokenAmount,
// feesHash,
// order.nft,
// order.nftId,
// propertiesHash,
// hashNonce
// ));
assembly {
if lt(order, 32) { invalid() } // Don't underflow memory.
let typeHashPos := sub(order, 32) // order - 32
let feesHashPos := add(order, 192) // order + (32 * 6)
let propertiesHashPos := add(order, 288) // order + (32 * 9)
let hashNoncePos := add(order, 320) // order + (32 * 10)
let typeHashMemBefore := mload(typeHashPos)
let feeHashMemBefore := mload(feesHashPos)
let propertiesHashMemBefore := mload(propertiesHashPos)
let hashNonceMemBefore := mload(hashNoncePos)
mstore(typeHashPos, _NFT_BUY_ORDER_TYPE_HASH)
mstore(feesHashPos, feesHash)
mstore(propertiesHashPos, propertiesHash)
mstore(hashNoncePos, hashNonce)
structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ )
mstore(typeHashPos, typeHashMemBefore)
mstore(feesHashPos, feeHashMemBefore)
mstore(propertiesHashPos, propertiesHashMemBefore)
mstore(hashNoncePos, hashNonceMemBefore)
}
return structHash;
}
/// @dev Get the struct hash of an ERC1155 sell order.
/// @param order The ERC1155 sell order.
/// @return structHash The struct hash of the order.
function getERC1155SellOrderStructHash(ERC1155SellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) {
bytes32 feesHash = _feesHash(order.fees);
// Hash in place, equivalent to:
// return keccak256(abi.encode(
// _ERC_1155_SELL_ORDER_TYPE_HASH,
// order.maker,
// order.taker,
// order.expiry,
// order.nonce,
// order.erc20Token,
// order.erc20TokenAmount,
// feesHash,
// order.erc1155Token,
// order.erc1155TokenId,
// order.erc1155TokenAmount,
// hashNonce
// ));
assembly {
if lt(order, 32) { invalid() } // Don't underflow memory.
let typeHashPos := sub(order, 32) // order - 32
let feesHashPos := add(order, 192) // order + (32 * 6)
let hashNoncePos := add(order, 320) // order + (32 * 10)
let typeHashMemBefore := mload(typeHashPos)
let feesHashMemBefore := mload(feesHashPos)
let hashNonceMemBefore := mload(hashNoncePos)
mstore(typeHashPos, _ERC_1155_SELL_ORDER_TYPE_HASH)
mstore(feesHashPos, feesHash)
mstore(hashNoncePos, hashNonce)
structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ )
mstore(typeHashPos, typeHashMemBefore)
mstore(feesHashPos, feesHashMemBefore)
mstore(hashNoncePos, hashNonceMemBefore)
}
return structHash;
}
/// @dev Get the struct hash of an ERC1155 buy order.
/// @param order The ERC1155 buy order.
/// @return structHash The struct hash of the order.
function getERC1155BuyOrderStructHash(ERC1155BuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) {
bytes32 propertiesHash = _propertiesHash(order.erc1155TokenProperties);
bytes32 feesHash = _feesHash(order.fees);
// Hash in place, equivalent to:
// return keccak256(abi.encode(
// _ERC_1155_BUY_ORDER_TYPE_HASH,
// order.maker,
// order.taker,
// order.expiry,
// order.nonce,
// order.erc20Token,
// order.erc20TokenAmount,
// feesHash,
// order.erc1155Token,
// order.erc1155TokenId,
// propertiesHash,
// order.erc1155TokenAmount,
// hashNonce
// ));
assembly {
if lt(order, 32) { invalid() } // Don't underflow memory.
let typeHashPos := sub(order, 32) // order - 32
let feesHashPos := add(order, 192) // order + (32 * 6)
let propertiesHashPos := add(order, 288) // order + (32 * 9)
let hashNoncePos := add(order, 352) // order + (32 * 11)
let typeHashMemBefore := mload(typeHashPos)
let feesHashMemBefore := mload(feesHashPos)
let propertiesHashMemBefore := mload(propertiesHashPos)
let hashNonceMemBefore := mload(hashNoncePos)
mstore(typeHashPos, _ERC_1155_BUY_ORDER_TYPE_HASH)
mstore(feesHashPos, feesHash)
mstore(propertiesHashPos, propertiesHash)
mstore(hashNoncePos, hashNonce)
structHash := keccak256(typeHashPos, 416 /* 32 * 13 */ )
mstore(typeHashPos, typeHashMemBefore)
mstore(feesHashPos, feesHashMemBefore)
mstore(propertiesHashPos, propertiesHashMemBefore)
mstore(hashNoncePos, hashNonceMemBefore)
}
return structHash;
}
// Hashes the `properties` array as part of computing the
// EIP-712 hash of an `ERC721Order` or `ERC1155Order`.
function _propertiesHash(Property[] memory properties) private pure returns (bytes32 propertiesHash) {
uint256 numProperties = properties.length;
// We give `properties.length == 0` and `properties.length == 1`
// special treatment because we expect these to be the most common.
if (numProperties == 0) {
propertiesHash = _EMPTY_ARRAY_KECCAK256;
} else if (numProperties == 1) {
Property memory property = properties[0];
if (address(property.propertyValidator) == address(0) && property.propertyData.length == 0) {
propertiesHash = _NULL_PROPERTY_STRUCT_HASH;
} else {
// propertiesHash = keccak256(abi.encodePacked(keccak256(abi.encode(
// _PROPERTY_TYPE_HASH,
// properties[0].propertyValidator,
// keccak256(properties[0].propertyData)
// ))));
bytes32 dataHash = keccak256(property.propertyData);
assembly {
// Load free memory pointer
let mem := mload(64)
mstore(mem, _PROPERTY_TYPE_HASH)
// property.propertyValidator
mstore(add(mem, 32), and(ADDRESS_MASK, mload(property)))
// keccak256(property.propertyData)
mstore(add(mem, 64), dataHash)
mstore(mem, keccak256(mem, 96))
propertiesHash := keccak256(mem, 32)
}
}
} else {
bytes32[] memory propertyStructHashArray = new bytes32[](numProperties);
for (uint256 i = 0; i < numProperties; i++) {
propertyStructHashArray[i] = keccak256(abi.encode(
_PROPERTY_TYPE_HASH, properties[i].propertyValidator, keccak256(properties[i].propertyData)));
}
assembly {
propertiesHash := keccak256(add(propertyStructHashArray, 32), mul(numProperties, 32))
}
}
}
// Hashes the `fees` array as part of computing the
// EIP-712 hash of an `ERC721Order` or `ERC1155Order`.
function _feesHash(Fee[] memory fees) private pure returns (bytes32 feesHash) {
uint256 numFees = fees.length;
// We give `fees.length == 0` and `fees.length == 1`
// special treatment because we expect these to be the most common.
if (numFees == 0) {
feesHash = _EMPTY_ARRAY_KECCAK256;
} else if (numFees == 1) {
// feesHash = keccak256(abi.encodePacked(keccak256(abi.encode(
// _FEE_TYPE_HASH,
// fees[0].recipient,
// fees[0].amount,
// keccak256(fees[0].feeData)
// ))));
Fee memory fee = fees[0];
bytes32 dataHash = keccak256(fee.feeData);
assembly {
// Load free memory pointer
let mem := mload(64)
mstore(mem, _FEE_TYPE_HASH)
// fee.recipient
mstore(add(mem, 32), and(ADDRESS_MASK, mload(fee)))
// fee.amount
mstore(add(mem, 64), mload(add(fee, 32)))
// keccak256(fee.feeData)
mstore(add(mem, 96), dataHash)
mstore(mem, keccak256(mem, 128))
feesHash := keccak256(mem, 32)
}
} else {
bytes32[] memory feeStructHashArray = new bytes32[](numFees);
for (uint256 i = 0; i < numFees; i++) {
feeStructHashArray[i] = keccak256(abi.encode(_FEE_TYPE_HASH, fees[i].recipient, fees[i].amount, keccak256(fees[i].feeData)));
}
assembly {
feesHash := keccak256(add(feeStructHashArray, 32), mul(numFees, 32))
}
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
/// @dev A library for validating signatures.
library LibSignature {
/// @dev Allowed signature types.
enum SignatureType {
EIP712,
PRESIGNED
}
/// @dev Encoded EC signature.
struct Signature {
// How to validate the signature.
SignatureType signatureType;
// EC Signature data.
uint8 v;
// EC Signature data.
bytes32 r;
// EC Signature data.
bytes32 s;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
interface IPropertyValidator {
/// @dev Checks that the given ERC721/ERC1155 asset satisfies the properties encoded in `propertyData`.
/// Should revert if the asset does not satisfy the specified properties.
/// @param tokenAddress The ERC721/ERC1155 token contract address.
/// @param tokenId The ERC721/ERC1155 tokenId of the asset to check.
/// @param propertyData Encoded properties or auxiliary data needed to perform the check.
function validateProperty(address tokenAddress, uint256 tokenId, bytes calldata propertyData) external view;
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
/// @dev EIP712 helpers for features.
abstract contract FixinEIP712 {
bytes32 private constant DOMAIN = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 private constant NAME = keccak256("ElementEx");
bytes32 private constant VERSION = keccak256("1.0.0");
uint256 private immutable CHAIN_ID;
constructor() {
uint256 chainId;
assembly { chainId := chainid() }
CHAIN_ID = chainId;
}
function _getEIP712Hash(bytes32 structHash) internal view returns (bytes32) {
return keccak256(abi.encodePacked(hex"1901", keccak256(abi.encode(DOMAIN, NAME, VERSION, CHAIN_ID, address(this))), structHash));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
/// @dev Helpers for moving tokens around.
abstract contract FixinTokenSpender {
// Mask of the lower 20 bytes of a bytes32.
uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff;
/// @dev Transfers ERC20 tokens from `owner` to `to`.
/// @param token The token to spend.
/// @param owner The owner of the tokens.
/// @param to The recipient of the tokens.
/// @param amount The amount of `token` to transfer.
function _transferERC20TokensFrom(IERC20 token, address owner, address to, uint256 amount) internal {
uint256 success;
assembly {
let ptr := mload(0x40) // free memory pointer
// selector for transferFrom(address,address,uint256)
mstore(ptr, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK))
mstore(add(ptr, 0x24), and(to, ADDRESS_MASK))
mstore(add(ptr, 0x44), amount)
success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, ptr, 32)
let rdsize := returndatasize()
// Check for ERC20 success. ERC20 tokens should return a boolean,
// but some don't. We accept 0-length return data as success, or at
// least 32 bytes that starts with a 32-byte boolean true.
success := and(
success, // call itself succeeded
or(
iszero(rdsize), // no return data, or
and(
iszero(lt(rdsize, 32)), // at least 32 bytes
eq(mload(ptr), 1) // starts with uint256(1)
)
)
)
}
require(success != 0, "_transferERC20/TRANSFER_FAILED");
}
/// @dev Transfers ERC20 tokens from ourselves to `to`.
/// @param token The token to spend.
/// @param to The recipient of the tokens.
/// @param amount The amount of `token` to transfer.
function _transferERC20Tokens(IERC20 token, address to, uint256 amount) internal {
uint256 success;
assembly {
let ptr := mload(0x40) // free memory pointer
// selector for transfer(address,uint256)
mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(ptr, 0x04), and(to, ADDRESS_MASK))
mstore(add(ptr, 0x24), amount)
success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x44, ptr, 32)
let rdsize := returndatasize()
// Check for ERC20 success. ERC20 tokens should return a boolean,
// but some don't. We accept 0-length return data as success, or at
// least 32 bytes that starts with a 32-byte boolean true.
success := and(
success, // call itself succeeded
or(
iszero(rdsize), // no return data, or
and(
iszero(lt(rdsize, 32)), // at least 32 bytes
eq(mload(ptr), 1) // starts with uint256(1)
)
)
)
}
require(success != 0, "_transferERC20/TRANSFER_FAILED");
}
/// @dev Transfers some amount of ETH to the given recipient and
/// reverts if the transfer fails.
/// @param recipient The recipient of the ETH.
/// @param amount The amount of ETH to transfer.
function _transferEth(address payable recipient, uint256 amount) internal {
if (amount > 0) {
(bool success,) = recipient.call{value: amount}("");
require(success, "_transferEth/TRANSFER_FAILED");
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2022 Element.Market
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IEtherToken is IERC20 {
/// @dev Wrap ether.
function deposit() external payable;
/// @dev Unwrap ether.
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
interface IFeeRecipient {
/// @dev A callback function invoked in the ERC721Feature for each ERC721
/// order fee that get paid. Integrators can make use of this callback
/// to implement arbitrary fee-handling logic, e.g. splitting the fee
/// between multiple parties.
/// @param tokenAddress The address of the token in which the received fee is
/// denominated. `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE` indicates
/// that the fee was paid in the native token (e.g. ETH).
/// @param amount The amount of the given token received.
/// @param feeData Arbitrary data encoded in the `Fee` used by this callback.
/// @return success The selector of this function (0x0190805e),
/// indicating that the callback succeeded.
function receiveZeroExFeeCallback(address tokenAddress, uint256 amount, bytes calldata feeData) external returns (bytes4 success);
}
// SPDX-License-Identifier: Apache-2.0
/*
Modifications Copyright 2022 Element.Market
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.13;
interface ITakerCallback {
/// @dev A taker callback function invoked in ERC721OrdersFeature and
/// ERC1155OrdersFeature between the maker -> taker transfer and
/// the taker -> maker transfer.
/// @param orderHash The hash of the order being filled when this
/// callback is invoked.
/// @param data Arbitrary data used by this callback.
/// @return success The selector of this function,
/// indicating that the callback succeeded.
function zeroExTakerCallback(bytes32 orderHash, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}