Transaction Hash:
Block:
15696560 at Oct-07-2022 01:35:59 PM +UTC
Transaction Fee:
0.001704776217771741 ETH
$4.36
Gas Used:
145,367 Gas / 11.727394923 Gwei
Emitted Events:
280 |
MafiaDogs.Transfer( from=0x8e8f48b03b3990576a4b09a581b1b2e8c7efebbc, to=[Sender] 0xb86bffa8edf161ba1b805ef5693c0eb0e46da733, tokenId=2227 )
|
281 |
GnosisSafeProxy.0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d( 0x3d0ce9bfc3ed7d6862dbb28b2dea94561fe714a1b4d019aa8af39730d1ad7c3d, 0x00000000000000000000000020f780a973856b93f63670377900c1d2a50a77c4, 0000000000000000000000000000000000000000000000000000f7d659b38800 )
|
282 |
ElementEx.0x8a0f8e04e7a35efabdc150b7d106308198a4f965a5d11badf768c5b8b273ac94( 0x8a0f8e04e7a35efabdc150b7d106308198a4f965a5d11badf768c5b8b273ac94, 0000000000000000000000008e8f48b03b3990576a4b09a581b1b2e8c7efebbc, 000000000000000000000000b86bffa8edf161ba1b805ef5693c0eb0e46da733, 000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, 00000000000000000000000000000000000000000000000000c0a79fba8eb800, 000000000000000000000000bedee3879a3c5107d8846bf7d91dbaacf8d42544, 00000000000000000000000000000000000000000000000000000000000008b3, 2a5200f92435f60eb6501be01bc9b10a3568b54935306c75212c4f6b02fb0f85 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x00cA6244...dcB7b75F3 | 36.5107513643058955 Eth | 36.5110238643058955 Eth | 0.0002725 | ||
0x20F780A9...2a50a77c4 | (Element: ElementEx) | ||||
0x473780de...e7F267dFc
Miner
| (MEV Builder: 0x473...dFc) | 0.056506160296484985 Eth | 0.056724210796484985 Eth | 0.0002180505 | |
0x8E8f48B0...8C7EfebBC | 0.175198943044477287 Eth | 0.229426443044477287 Eth | 0.0542275 | ||
0xb86Bffa8...0e46dA733 |
0.065101882334788493 Eth
Nonce: 14
|
0.008897106117016752 Eth
Nonce: 15
| 0.056204776217771741 | ||
0xbedEE387...cf8d42544 |
Execution Trace
ETH 0.0545
ElementEx.5f57685e( )
ETH 0.0545
ERC721OrdersFeature.buyERC721( sellOrder=[{name:maker, type:address, order:1, indexed:false, value:0x8E8f48B03B3990576a4B09A581b1b2e8C7EfebBC, valueString:0x8E8f48B03B3990576a4B09A581b1b2e8C7EfebBC}, {name:taker, type:address, order:2, indexed:false, value:0x0000000000000000000000000000000000000000, valueString:0x0000000000000000000000000000000000000000}, {name:expiry, type:uint256, order:3, indexed:false, value:7150558428480740823, valueString:7150558428480740823}, {name:nonce, type:uint256, order:4, indexed:false, value:8, valueString:8}, {name:erc20Token, type:address, order:5, indexed:false, value:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, valueString:0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE}, {name:erc20TokenAmount, type:uint256, order:6, indexed:false, value:54227500000000000, valueString:54227500000000000}, {name:fees, type:tuple[], order:7, indexed:false}, {name:nft, type:address, order:8, indexed:false, value:0xbedEE3879a3c5107d8846bF7d91dbaacf8d42544, valueString:0xbedEE3879a3c5107d8846bF7d91dbaacf8d42544}, {name:nftId, type:uint256, order:9, indexed:false, value:2227, valueString:2227}], 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:54374D9D05AC4FC09808A96D36E22BBA9067421AC2EB7F47F23408ED93CD5A1C, valueString:54374D9D05AC4FC09808A96D36E22BBA9067421AC2EB7F47F23408ED93CD5A1C}, {name:s, type:bytes32, order:4, indexed:false, value:2FEC8F31BE9D5BEDFE0C084CE5B218D0FF4C50BEF9C55D6B4190161DD736053D, valueString:2FEC8F31BE9D5BEDFE0C084CE5B218D0FF4C50BEF9C55D6B4190161DD736053D}] )
-
Null: 0x000...001.2a5200f9( )
-
MafiaDogs.transferFrom( from=0x8E8f48B03B3990576a4B09A581b1b2e8C7EfebBC, to=0xb86Bffa8eDF161BA1b805Ef5693C0eb0e46dA733, tokenId=2227 )
- ETH 0.0542275
0x8e8f48b03b3990576a4b09a581b1b2e8c7efebbc.CALL( )
ETH 0.0002725
GnosisSafeProxy.CALL( )
- ETH 0.0002725
GnosisSafe.DELEGATECALL( )
- ETH 0.0002725
-
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 5: ElementEx
File 2 of 5: MafiaDogs
File 3 of 5: GnosisSafeProxy
File 4 of 5: ERC721OrdersFeature
File 5 of 5: GnosisSafe
// 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 5: MafiaDogs
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./ERC4907.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; contract MafiaDogs is ERC4907, Ownable { string public baseTokenURI; bool public presaleIsActive; bool public publicSaleIsActive; uint256 public presalePrice; uint256 public publicSalePrice; uint256 public alMints; uint256 public ogMints; uint256 public maxMints; address private _signer; uint256 public constant MAX_SUPPLY = 7777; uint8 private constant _PUBLIC_MINT = 0; uint8 private constant _AL_MINT = 1; uint8 private constant _OG_MINT = 2; constructor( string memory _baseTokenURI, uint256 _presalePrice, uint256 _publicSalePrice, address signer_, uint256 _alMints, uint256 _ogMints, uint256 _maxMints ) ERC721A("MafiaDogs", "MD") { baseTokenURI = _baseTokenURI; presalePrice = _presalePrice; publicSalePrice = _publicSalePrice; _signer = signer_; setMaxMints(_alMints, _ogMints, _maxMints); } function adminMint(address recipient, uint256 quantity) external onlyOwner { require(recipient != address(0), "MafiaDogs: mint to the zero address"); require(totalSupply() + quantity <= MAX_SUPPLY, "MafiaDogs: MAX_SUPPLY exceeded"); _mint(recipient, quantity); } function mint(uint8 mintType, uint256 quantity, bytes memory signature) external payable { require(tx.origin == msg.sender, "MafiaDogs: externally-owned account only"); require(_verifySignature(mintType, signature), "MafiaDogs: invalid signature"); require(totalSupply() + quantity <= MAX_SUPPLY, "MafiaDogs: MAX_SUPPLY exceeded"); uint256 costToMint; if (mintType == _AL_MINT) { require(presaleIsActive, "MafiaDogs: presale is not active"); require(_numberMinted(msg.sender) + quantity <= alMints, "MafiaDogs: alMints exceeded"); costToMint = quantity * presalePrice; } else if (mintType == _OG_MINT) { require(presaleIsActive, "MafiaDogs: presale is not active"); require(_numberMinted(msg.sender) + quantity <= ogMints, "MafiaDogs: ogMints exceeded"); costToMint = quantity * presalePrice; } else if (mintType == _PUBLIC_MINT) { require(publicSaleIsActive, "MafiaDogs: public sale is not active"); require(_numberMinted(msg.sender) + quantity <= maxMints, "MafiaDogs: maxMints exceeded"); costToMint = quantity * publicSalePrice; } else { revert("MafiaDogs: invalid mint type"); } require(msg.value >= costToMint, "MafiaDogs: insufficient value"); if (msg.value > costToMint) { payable(msg.sender).transfer(msg.value - costToMint); } _mint(msg.sender, quantity); } function setBaseURI(string memory _baseTokenURI) external onlyOwner { baseTokenURI = _baseTokenURI; } function setSigner(address signer_) external onlyOwner { _signer = signer_; } function setSaleState(bool _presaleIsActive, bool _publicSaleIsActive) external onlyOwner { presaleIsActive = _presaleIsActive; publicSaleIsActive = _publicSaleIsActive; } function setPrices(uint256 _presalePrice, uint256 _publicSalePrice) external onlyOwner { presalePrice = _presalePrice; publicSalePrice = _publicSalePrice; } function setMaxMints(uint256 _alMints, uint256 _ogMints, uint256 _maxMints) public onlyOwner { require(_alMints <= _ogMints && _ogMints <= _maxMints, "MafiaDogs: invalid arguments"); alMints = _alMints; ogMints = _ogMints; maxMints = _maxMints; } function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } function numberMinted(address addr) external view returns (uint256) { return _numberMinted(addr); } function _baseURI() internal view override returns (string memory) { return baseTokenURI; } function _verifySignature(uint8 type_, bytes memory signature) private view returns (bool) { return (ECDSA.recover(keccak256(abi.encodePacked(type_, msg.sender)), signature) == _signer); } } // SPDX-License-Identifier: CC0-1.0 pragma solidity ^0.8.0; import "./interfaces/IERC4907.sol"; import "erc721a/contracts/ERC721A.sol"; /* * Originally based on eip-4907 reference implementation: https://eips.ethereum.org/EIPS/eip-4907#reference-implementation */ abstract contract ERC4907 is ERC721A, IERC4907 { struct UserInfo { address user; // address of user role uint64 expires; // unix timestamp, user expires } mapping (uint256 => UserInfo) internal _users; /// @notice set the user and expires of a NFT /// @dev The zero address indicates there is no user /// Throws if `tokenId` is not valid NFT /// @param user The new user of the NFT /// @param expires UNIX timestamp, The new user could use the NFT before expires function setUser(uint256 tokenId, address user, uint64 expires) public virtual{ // check if message sender is allowed to manage token address tokenOwner = ownerOf(tokenId); address approvedAddress = getApproved(tokenId); if (msg.sender != tokenOwner && msg.sender != approvedAddress) require(isApprovedForAll(tokenOwner, msg.sender), "ERC4907: caller is not owner nor approved"); UserInfo storage info = _users[tokenId]; info.user = user; info.expires = expires; emit UpdateUser(tokenId,user,expires); } /// @notice Get the user address of an NFT /// @dev The zero address indicates that there is no user or the user is expired /// @param tokenId The NFT to get the user address for /// @return The user address for this NFT function userOf(uint256 tokenId)public view virtual returns(address){ if( uint256(_users[tokenId].expires) >= block.timestamp){ return _users[tokenId].user; } else{ return address(0); } } /// @notice Get the user expires of an NFT /// @dev The zero value indicates that there is no user /// @param tokenId The NFT to get the user expires for /// @return The user expires for this NFT function userExpires(uint256 tokenId) public view virtual returns(uint256){ return _users[tokenId].expires; } /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC4907).interfaceId || super.supportsInterface(interfaceId); } function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual override{ super._beforeTokenTransfers(from, to, startTokenId, quantity); if (from != to && _users[startTokenId].user != address(0)) { delete _users[startTokenId]; emit UpdateUser(startTokenId, address(0), 0); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.3) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\ 32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\ ", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\\x19\\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: CC0-1.0 pragma solidity ^0.8.0; interface IERC4907 { // Logged when the user of a token assigns a new user or updates expires /// @notice Emitted when the `user` of an NFT or the `expires` of the `user` is changed /// The zero address for user indicates that there is no user address event UpdateUser(uint256 indexed tokenId, address indexed user, uint64 expires); /// @notice set the user and expires of a NFT /// @dev The zero address indicates there is no user /// Throws if `tokenId` is not valid NFT /// @param user The new user of the NFT /// @param expires UNIX timestamp, The new user could use the NFT before expires function setUser(uint256 tokenId, address user, uint64 expires) external ; /// @notice Get the user address of an NFT /// @dev The zero address indicates that there is no user or the user is expired /// @param tokenId The NFT to get the user address for /// @return The user address for this NFT function userOf(uint256 tokenId) external view returns(address); /// @notice Get the user expires of an NFT /// @dev The zero value indicates that there is no user /// @param tokenId The NFT to get the user expires for /// @return The user expires for this NFT function userExpires(uint256 tokenId) external view returns(uint256); } // SPDX-License-Identifier: MIT // ERC721A Contracts v4.2.2 // Creator: Chiru Labs pragma solidity ^0.8.4; import './IERC721A.sol'; /** * @dev Interface of ERC721 token receiver. */ interface ERC721A__IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC721A * * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721) * Non-Fungible Token Standard, including the Metadata extension. * Optimized for lower gas during batch mints. * * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...) * starting from `_startTokenId()`. * * Assumptions: * * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is IERC721A { // Reference type for token approval. struct TokenApprovalRef { address value; } // ============================================================= // CONSTANTS // ============================================================= // Mask of an entry in packed address data. uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1; // The bit position of `numberMinted` in packed address data. uint256 private constant _BITPOS_NUMBER_MINTED = 64; // The bit position of `numberBurned` in packed address data. uint256 private constant _BITPOS_NUMBER_BURNED = 128; // The bit position of `aux` in packed address data. uint256 private constant _BITPOS_AUX = 192; // Mask of all 256 bits in packed address data except the 64 bits for `aux`. uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1; // The bit position of `startTimestamp` in packed ownership. uint256 private constant _BITPOS_START_TIMESTAMP = 160; // The bit mask of the `burned` bit in packed ownership. uint256 private constant _BITMASK_BURNED = 1 << 224; // The bit position of the `nextInitialized` bit in packed ownership. uint256 private constant _BITPOS_NEXT_INITIALIZED = 225; // The bit mask of the `nextInitialized` bit in packed ownership. uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225; // The bit position of `extraData` in packed ownership. uint256 private constant _BITPOS_EXTRA_DATA = 232; // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`. uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1; // The mask of the lower 160 bits for addresses. uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1; // The maximum `quantity` that can be minted with {_mintERC2309}. // This limit is to prevent overflows on the address data entries. // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309} // is required to cause an overflow, which is unrealistic. uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000; // The `Transfer` event signature is given by: // `keccak256(bytes("Transfer(address,address,uint256)"))`. bytes32 private constant _TRANSFER_EVENT_SIGNATURE = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; // ============================================================= // STORAGE // ============================================================= // The next token ID to be minted. uint256 private _currentIndex; // The number of tokens burned. uint256 private _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. // See {_packedOwnershipOf} implementation for details. // // Bits Layout: // - [0..159] `addr` // - [160..223] `startTimestamp` // - [224] `burned` // - [225] `nextInitialized` // - [232..255] `extraData` mapping(uint256 => uint256) private _packedOwnerships; // Mapping owner address to address data. // // Bits Layout: // - [0..63] `balance` // - [64..127] `numberMinted` // - [128..191] `numberBurned` // - [192..255] `aux` mapping(address => uint256) private _packedAddressData; // Mapping from token ID to approved address. mapping(uint256 => TokenApprovalRef) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // ============================================================= // CONSTRUCTOR // ============================================================= constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } // ============================================================= // TOKEN COUNTING OPERATIONS // ============================================================= /** * @dev Returns the starting token ID. * To change the starting token ID, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Returns the next token ID to be minted. */ function _nextTokenId() internal view virtual returns (uint256) { return _currentIndex; } /** * @dev Returns the total number of tokens in existence. * Burned tokens will reduce the count. * To get the total number of tokens minted, please see {_totalMinted}. */ function totalSupply() public view virtual override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than `_currentIndex - _startTokenId()` times. unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * @dev Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view virtual returns (uint256) { // Counter underflow is impossible as `_currentIndex` does not decrement, // and it is initialized to `_startTokenId()`. unchecked { return _currentIndex - _startTokenId(); } } /** * @dev Returns the total number of tokens burned. */ function _totalBurned() internal view virtual returns (uint256) { return _burnCounter; } // ============================================================= // ADDRESS DATA OPERATIONS // ============================================================= /** * @dev Returns the number of tokens in `owner`'s account. */ function balanceOf(address owner) public view virtual override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return uint64(_packedAddressData[owner] >> _BITPOS_AUX); } /** * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal virtual { uint256 packed = _packedAddressData[owner]; uint256 auxCasted; // Cast `aux` with assembly to avoid redundant masking. assembly { auxCasted := aux } packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX); _packedAddressData[owner] = packed; } // ============================================================= // IERC165 // ============================================================= /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This function call must use less than 30000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { // The interface IDs are constants representing the first 4 bytes // of the XOR of all function selectors in the interface. // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165) // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`) return interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165. interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721. interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata. } // ============================================================= // IERC721Metadata // ============================================================= /** * @dev Returns the token collection name. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the token collection symbol. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : ''; } /** * @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, it can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } // ============================================================= // OWNERSHIPS OPERATIONS // ============================================================= /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return address(uint160(_packedOwnershipOf(tokenId))); } /** * @dev Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around over time. */ function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnershipOf(tokenId)); } /** * @dev Returns the unpacked `TokenOwnership` struct at `index`. */ function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnerships[index]); } /** * @dev Initializes the ownership slot minted at `index` for efficiency purposes. */ function _initializeOwnershipAt(uint256 index) internal virtual { if (_packedOwnerships[index] == 0) { _packedOwnerships[index] = _packedOwnershipOf(index); } } /** * Returns the packed ownership data of `tokenId`. */ function _packedOwnershipOf(uint256 tokenId) private view returns (uint256) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { uint256 packed = _packedOwnerships[curr]; // If not burned. if (packed & _BITMASK_BURNED == 0) { // Invariant: // There will always be an initialized ownership slot // (i.e. `ownership.addr != address(0) && ownership.burned == false`) // before an unintialized ownership slot // (i.e. `ownership.addr == address(0) && ownership.burned == false`) // Hence, `curr` will not underflow. // // We can directly compare the packed value. // If the address is zero, packed will be zero. while (packed == 0) { packed = _packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); } /** * @dev Returns the unpacked `TokenOwnership` struct from `packed`. */ function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) { ownership.addr = address(uint160(packed)); ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP); ownership.burned = packed & _BITMASK_BURNED != 0; ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA); } /** * @dev Packs ownership data into a single uint256. */ function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) { assembly { // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean. owner := and(owner, _BITMASK_ADDRESS) // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`. result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags)) } } /** * @dev Returns the `nextInitialized` flag set if `quantity` equals 1. */ function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) { // For branchless setting of the `nextInitialized` flag. assembly { // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`. result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1)) } } // ============================================================= // APPROVAL OPERATIONS // ============================================================= /** * @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) public virtual override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } _tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); } /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId].value; } /** * @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) public virtual override { if (operator == _msgSenderERC721A()) revert ApproveToCaller(); _operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); } /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @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. See {_mint}. */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && // If within bounds, _packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned. } /** * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`. */ function _isSenderApprovedOrOwner( address approvedAddress, address owner, address msgSender ) private pure returns (bool result) { assembly { // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean. owner := and(owner, _BITMASK_ADDRESS) // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean. msgSender := and(msgSender, _BITMASK_ADDRESS) // `msgSender == owner || msgSender == approvedAddress`. result := or(eq(msgSender, owner), eq(msgSender, approvedAddress)) } } /** * @dev Returns the storage slot and value for the approved address of `tokenId`. */ function _getApprovedSlotAndAddress(uint256 tokenId) private view returns (uint256 approvedAddressSlot, address approvedAddress) { TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId]; // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId]`. assembly { approvedAddressSlot := tokenApproval.slot approvedAddress := sload(approvedAddressSlot) } } // ============================================================= // TRANSFER OPERATIONS // ============================================================= /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) public virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId); // The nested ifs save around 20+ gas over a compound boolean condition. if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner. assembly { if approvedAddress { // This is equivalent to `delete _tokenApprovals[tokenId]`. sstore(approvedAddressSlot, 0) } } // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256. unchecked { // We can directly increment and decrement the balances. --_packedAddressData[from]; // Updates: `balance -= 1`. ++_packedAddressData[to]; // Updates: `balance += 1`. // Updates: // - `address` to the next owner. // - `startTimestamp` to the timestamp of transfering. // - `burned` to `false`. // - `nextInitialized` to `true`. _packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); // If the next slot may not have been initialized (i.e. `nextInitialized == false`) . if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; // If the next slot's address is zero and not burned (i.e. packed value is zero). if (_packedOwnerships[nextTokenId] == 0) { // If the next slot is within bounds. if (nextTokenId != _currentIndex) { // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`. _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @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 memory _data ) public virtual override { transferFrom(from, to, tokenId); if (to.code.length != 0) if (!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Hook that is called before a set of serially-ordered token IDs * are about to be transferred. This includes minting. * And also called before burning one token. * * `startTokenId` - the first token ID to be transferred. * `quantity` - the amount to be transferred. * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token IDs * have been transferred. This includes minting. * And also called after one token has been burned. * * `startTokenId` - the first token ID to be transferred. * `quantity` - the amount to be transferred. * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * `from` - Previous owner of the given token ID. * `to` - Target address that will receive the token. * `tokenId` - Token ID to be fred. * `_data` - Optional data to send along with the call. * * Returns whether the call correctly returned the expected magic value. */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns ( bytes4 retval ) { return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } // ============================================================= // MINT OPERATIONS // ============================================================= /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event for each mint. */ function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // `balance` and `numberMinted` have a maximum limit of 2**64. // `tokenId` has a maximum limit of 2**256. unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the `balance` and `numberMinted`. _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); uint256 toMasked; uint256 end = startTokenId + quantity; // Use assembly to loop and emit the `Transfer` event for gas savings. assembly { // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean. toMasked := and(to, _BITMASK_ADDRESS) // Emit the `Transfer` event. log4( 0, // Start of data (0, since no data). 0, // End of data (0, since no data). _TRANSFER_EVENT_SIGNATURE, // Signature. 0, // `address(0)`. toMasked, // `to`. startTokenId // `tokenId`. ) for { let tokenId := add(startTokenId, 1) } iszero(eq(tokenId, end)) { tokenId := add(tokenId, 1) } { // Emit the `Transfer` event. Similar to above. log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } if (toMasked == 0) revert MintToZeroAddress(); _currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * This function is intended for efficient minting only during contract creation. * * It emits only one {ConsecutiveTransfer} as defined in * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309), * instead of a sequence of {Transfer} event(s). * * Calling this function outside of contract creation WILL make your contract * non-compliant with the ERC721 standard. * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309 * {ConsecutiveTransfer} event is only permissible during contract creation. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {ConsecutiveTransfer} event. */ function _mintERC2309(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are unrealistic due to the above check for `quantity` to be below the limit. unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the `balance` and `numberMinted`. _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to); _currentIndex = startTokenId + quantity; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * See {_mint}. * * Emits a {Transfer} event for each mint. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity); unchecked { if (to.code.length != 0) { uint256 end = _currentIndex; uint256 index = end - quantity; do { if (!_checkContractOnERC721Received(address(0), to, index++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (index < end); // Reentrancy protection. if (_currentIndex != end) revert(); } } } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal virtual { _safeMint(to, quantity, ''); } // ============================================================= // BURN OPERATIONS // ============================================================= /** * @dev Equivalent to `_burn(tokenId, false)`. */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { // The nested ifs save around 20+ gas over a compound boolean condition. if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) if (!isApprovedForAll(from, _msgSenderERC721A())) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner. assembly { if approvedAddress { // This is equivalent to `delete _tokenApprovals[tokenId]`. sstore(approvedAddressSlot, 0) } } // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256. unchecked { // Updates: // - `balance -= 1`. // - `numberBurned += 1`. // // We can directly decrement the balance, and increment the number burned. // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`. _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; // Updates: // - `address` to the last owner. // - `startTimestamp` to the timestamp of burning. // - `burned` to `true`. // - `nextInitialized` to `true`. _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); // If the next slot may not have been initialized (i.e. `nextInitialized == false`) . if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; // If the next slot's address is zero and not burned (i.e. packed value is zero). if (_packedOwnerships[nextTokenId] == 0) { // If the next slot is within bounds. if (nextTokenId != _currentIndex) { // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`. _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } // ============================================================= // EXTRA DATA OPERATIONS // ============================================================= /** * @dev Directly sets the extra data for the ownership data `index`. */ function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual { uint256 packed = _packedOwnerships[index]; if (packed == 0) revert OwnershipNotInitializedForExtraData(); uint256 extraDataCasted; // Cast `extraData` with assembly to avoid redundant masking. assembly { extraDataCasted := extraData } packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA); _packedOwnerships[index] = packed; } /** * @dev Called during each token transfer to set the 24bit `extraData` field. * Intended to be overridden by the cosumer contract. * * `previousExtraData` - the value of `extraData` before transfer. * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _extraData( address from, address to, uint24 previousExtraData ) internal view virtual returns (uint24) {} /** * @dev Returns the next extra data for the packed ownership data. * The returned result is shifted into position. */ function _nextExtraData( address from, address to, uint256 prevOwnershipPacked ) private view returns (uint256) { uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA); return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA; } // ============================================================= // OTHER OPERATIONS // ============================================================= /** * @dev Returns the message sender (defaults to `msg.sender`). * * If you are writing GSN compatible contracts, you need to override this function. */ function _msgSenderERC721A() internal view virtual returns (address) { return msg.sender; } /** * @dev Converts a uint256 to its ASCII string decimal representation. */ function _toString(uint256 value) internal pure virtual returns (string memory str) { assembly { // The maximum value of a uint256 contains 78 digits (1 byte per digit), // but we allocate 0x80 bytes to keep the free memory pointer 32-byte word aliged. // We will need 1 32-byte word to store the length, // and 3 32-byte words to store a maximum of 78 digits. Total: 0x20 + 3 * 0x20 = 0x80. str := add(mload(0x40), 0x80) // Update the free memory pointer to allocate. mstore(0x40, str) // Cache the end of the memory to calculate the length later. let end := str // We write the string from rightmost digit to leftmost digit. // The following is essentially a do-while loop that also handles the zero case. // prettier-ignore for { let temp := value } 1 {} { str := sub(str, 1) // Write the character to the pointer. // The ASCII index of the '0' character is 48. mstore8(str, add(48, mod(temp, 10))) // Keep dividing `temp` until zero. temp := div(temp, 10) // prettier-ignore if iszero(temp) { break } } let length := sub(end, str) // Move the pointer 32 bytes leftwards to make room for the length. str := sub(str, 0x20) // Store the length. mstore(str, length) } } } // SPDX-License-Identifier: MIT // ERC721A Contracts v4.2.2 // Creator: Chiru Labs pragma solidity ^0.8.4; /** * @dev Interface of ERC721A. */ interface IERC721A { /** * The caller must own the token or be an approved operator. */ error ApprovalCallerNotOwnerNorApproved(); /** * The token does not exist. */ error ApprovalQueryForNonexistentToken(); /** * The caller cannot approve to their own address. */ error ApproveToCaller(); /** * Cannot query the balance for the zero address. */ error BalanceQueryForZeroAddress(); /** * Cannot mint to the zero address. */ error MintToZeroAddress(); /** * The quantity of tokens minted must be more than zero. */ error MintZeroQuantity(); /** * The token does not exist. */ error OwnerQueryForNonexistentToken(); /** * The caller must own the token or be an approved operator. */ error TransferCallerNotOwnerNorApproved(); /** * The token must be owned by `from`. */ error TransferFromIncorrectOwner(); /** * Cannot safely transfer to a contract that does not implement the * ERC721Receiver interface. */ error TransferToNonERC721ReceiverImplementer(); /** * Cannot transfer to the zero address. */ error TransferToZeroAddress(); /** * The token does not exist. */ error URIQueryForNonexistentToken(); /** * The `quantity` minted with ERC2309 exceeds the safety limit. */ error MintERC2309QuantityExceedsLimit(); /** * The `extraData` cannot be set on an unintialized ownership slot. */ error OwnershipNotInitializedForExtraData(); // ============================================================= // STRUCTS // ============================================================= struct TokenOwnership { // The address of the owner. address addr; // Stores the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}. uint24 extraData; } // ============================================================= // TOKEN COUNTERS // ============================================================= /** * @dev Returns the total number of tokens in existence. * Burned tokens will reduce the count. * To get the total number of tokens minted, please see {_totalMinted}. */ function totalSupply() external view returns (uint256); // ============================================================= // IERC165 // ============================================================= /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This function call must use less than 30000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); // ============================================================= // IERC721 // ============================================================= /** * @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, bytes calldata data ) external; /** * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} * whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token * by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the * zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} * for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll}. */ function isApprovedForAll(address owner, address operator) external view returns (bool); // ============================================================= // IERC721Metadata // ============================================================= /** * @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); // ============================================================= // IERC2309 // ============================================================= /** * @dev Emitted when tokens in `fromTokenId` to `toTokenId` * (inclusive) is transferred from `from` to `to`, as defined in the * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard. * * See {_mintERC2309} for more details. */ event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } }
File 3 of 5: GnosisSafeProxy
// SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain /// @author Richard Meissner - <[email protected]> interface IProxy { function masterCopy() external view returns (address); } /// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract GnosisSafeProxy { // singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated. // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt` address internal singleton; /// @dev Constructor function sets address of singleton contract. /// @param _singleton Singleton address. constructor(address _singleton) { require(_singleton != address(0), "Invalid singleton address provided"); singleton = _singleton; } /// @dev Fallback function forwards all transactions and returns all received return data. fallback() external payable { // solhint-disable-next-line no-inline-assembly assembly { let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff) // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) { mstore(0, _singleton) return(0, 0x20) } calldatacopy(0, 0, calldatasize()) let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) if eq(success, 0) { revert(0, returndatasize()) } return(0, returndatasize()) } } } /// @title Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @author Stefan George - <[email protected]> contract GnosisSafeProxyFactory { event ProxyCreation(GnosisSafeProxy proxy, address singleton); /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param singleton Address of singleton contract. /// @param data Payload for message call sent to new proxy contract. function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) { proxy = new GnosisSafeProxy(singleton); if (data.length > 0) // solhint-disable-next-line no-inline-assembly assembly { if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit ProxyCreation(proxy, singleton); } /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed. function proxyRuntimeCode() public pure returns (bytes memory) { return type(GnosisSafeProxy).runtimeCode; } /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address. function proxyCreationCode() public pure returns (bytes memory) { return type(GnosisSafeProxy).creationCode; } /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer. /// This method is only meant as an utility to be called from other methods /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function deployProxyWithNonce( address _singleton, bytes memory initializer, uint256 saltNonce ) internal returns (GnosisSafeProxy proxy) { // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce)); bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton))); // solhint-disable-next-line no-inline-assembly assembly { proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt) } require(address(proxy) != address(0), "Create2 call failed"); } /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function createProxyWithNonce( address _singleton, bytes memory initializer, uint256 saltNonce ) public returns (GnosisSafeProxy proxy) { proxy = deployProxyWithNonce(_singleton, initializer, saltNonce); if (initializer.length > 0) // solhint-disable-next-line no-inline-assembly assembly { if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) { revert(0, 0) } } emit ProxyCreation(proxy, _singleton); } /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. /// @param callback Callback that will be invoced after the new proxy contract has been successfully deployed and initialized. function createProxyWithCallback( address _singleton, bytes memory initializer, uint256 saltNonce, IProxyCreationCallback callback ) public returns (GnosisSafeProxy proxy) { uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback))); proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback); if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce); } /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce` /// This method is only meant for address calculation purpose when you use an initializer that would revert, /// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory. /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function calculateCreateProxyWithNonceAddress( address _singleton, bytes calldata initializer, uint256 saltNonce ) external returns (GnosisSafeProxy proxy) { proxy = deployProxyWithNonce(_singleton, initializer, saltNonce); revert(string(abi.encodePacked(proxy))); } } interface IProxyCreationCallback { function proxyCreated( GnosisSafeProxy proxy, address _singleton, bytes calldata initializer, uint256 saltNonce ) external; }
File 4 of 5: 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); } }
File 5 of 5: GnosisSafe
// SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "./base/ModuleManager.sol"; import "./base/OwnerManager.sol"; import "./base/FallbackManager.sol"; import "./base/GuardManager.sol"; import "./common/EtherPaymentFallback.sol"; import "./common/Singleton.sol"; import "./common/SignatureDecoder.sol"; import "./common/SecuredTokenTransfer.sol"; import "./common/StorageAccessible.sol"; import "./interfaces/ISignatureValidator.sol"; import "./external/GnosisSafeMath.sol"; /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract GnosisSafe is EtherPaymentFallback, Singleton, ModuleManager, OwnerManager, SignatureDecoder, SecuredTokenTransfer, ISignatureValidatorConstants, FallbackManager, StorageAccessible, GuardManager { using GnosisSafeMath for uint256; string public constant VERSION = "1.3.0"; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)" // ); bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8; event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler); event ApproveHash(bytes32 indexed approvedHash, address indexed owner); event SignMsg(bytes32 indexed msgHash); event ExecutionFailure(bytes32 txHash, uint256 payment); event ExecutionSuccess(bytes32 txHash, uint256 payment); uint256 public nonce; bytes32 private _deprecatedDomainSeparator; // Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners mapping(bytes32 => uint256) public signedMessages; // Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners mapping(address => mapping(bytes32 => uint256)) public approvedHashes; // This constructor ensures that this contract can only be used as a master copy for Proxy contracts constructor() { // By setting the threshold it is not possible to call setup anymore, // so we create a Safe with 0 owners and threshold 1. // This is an unusable Safe, perfect for the singleton threshold = 1; } /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. /// @param to Contract address for optional delegate call. /// @param data Data payload for optional delegate call. /// @param fallbackHandler Handler for fallback calls to this contract /// @param paymentToken Token that should be used for the payment (0 is ETH) /// @param payment Value that should be paid /// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin) function setup( address[] calldata _owners, uint256 _threshold, address to, bytes calldata data, address fallbackHandler, address paymentToken, uint256 payment, address payable paymentReceiver ) external { // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice setupOwners(_owners, _threshold); if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler); // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules setupModules(to, data); if (payment > 0) { // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself) // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment handlePayment(payment, 0, 1, paymentToken, paymentReceiver); } emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler); } /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction. /// Note: The fees are always transferred, even if the user transaction fails. /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @param safeTxGas Gas that should be used for the Safe transaction. /// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Gas price that should be used for the payment calculation. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) function execTransaction( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures ) public payable virtual returns (bool success) { bytes32 txHash; // Use scope here to limit variable lifetime and prevent `stack too deep` errors { bytes memory txHashData = encodeTransactionData( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info nonce ); // Increase nonce and execute transaction. nonce++; txHash = keccak256(txHashData); checkSignatures(txHash, txHashData, signatures); } address guard = getGuard(); { if (guard != address(0)) { Guard(guard).checkTransaction( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info signatures, msg.sender ); } } // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500) // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150 require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010"); // Use scope here to limit variable lifetime and prevent `stack too deep` errors { uint256 gasUsed = gasleft(); // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas) // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas); gasUsed = gasUsed.sub(gasleft()); // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert require(success || safeTxGas != 0 || gasPrice != 0, "GS013"); // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls uint256 payment = 0; if (gasPrice > 0) { payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver); } if (success) emit ExecutionSuccess(txHash, payment); else emit ExecutionFailure(txHash, payment); } { if (guard != address(0)) { Guard(guard).checkAfterExecution(txHash, success); } } } function handlePayment( uint256 gasUsed, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver ) private returns (uint256 payment) { // solhint-disable-next-line avoid-tx-origin address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver; if (gasToken == address(0)) { // For ETH we will only adjust the gas price to not be higher than the actual used gas price payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice); require(receiver.send(payment), "GS011"); } else { payment = gasUsed.add(baseGas).mul(gasPrice); require(transferToken(gasToken, receiver, payment), "GS012"); } } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. */ function checkSignatures( bytes32 dataHash, bytes memory data, bytes memory signatures ) public view { // Load threshold to avoid multiple storage loads uint256 _threshold = threshold; // Check that a threshold is set require(_threshold > 0, "GS001"); checkNSignatures(dataHash, data, signatures, _threshold); } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. * @param requiredSignatures Amount of required valid signatures. */ function checkNSignatures( bytes32 dataHash, bytes memory data, bytes memory signatures, uint256 requiredSignatures ) public view { // Check that the provided signature data is not too short require(signatures.length >= requiredSignatures.mul(65), "GS020"); // There cannot be an owner with address 0. address lastOwner = address(0); address currentOwner; uint8 v; bytes32 r; bytes32 s; uint256 i; for (i = 0; i < requiredSignatures; i++) { (v, r, s) = signatureSplit(signatures, i); if (v == 0) { // If v is 0 then it is a contract signature // When handling contract signatures the address of the contract is encoded into r currentOwner = address(uint160(uint256(r))); // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes // This check is not completely accurate, since it is possible that more signatures than the threshold are send. // Here we only check that the pointer is not pointing inside the part that is being processed require(uint256(s) >= requiredSignatures.mul(65), "GS021"); // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes) require(uint256(s).add(32) <= signatures.length, "GS022"); // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length uint256 contractSignatureLen; // solhint-disable-next-line no-inline-assembly assembly { contractSignatureLen := mload(add(add(signatures, s), 0x20)) } require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023"); // Check signature bytes memory contractSignature; // solhint-disable-next-line no-inline-assembly assembly { // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s contractSignature := add(add(signatures, s), 0x20) } require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024"); } else if (v == 1) { // If v is 1 then it is an approved hash // When handling approved hashes the address of the approver is encoded into r currentOwner = address(uint160(uint256(r))); // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025"); } else if (v > 30) { // If v > 30 then default va (27,28) has been adjusted for eth_sign flow // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover currentOwner = ecrecover(keccak256(abi.encodePacked("\\x19Ethereum Signed Message:\ 32", dataHash)), v - 4, r, s); } else { // Default is the ecrecover flow with the provided data hash // Use ecrecover with the messageHash for EOA signatures currentOwner = ecrecover(dataHash, v, r, s); } require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026"); lastOwner = currentOwner; } } /// @dev Allows to estimate a Safe transaction. /// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data. /// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction` /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs). /// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version. function requiredTxGas( address to, uint256 value, bytes calldata data, Enum.Operation operation ) external returns (uint256) { uint256 startGas = gasleft(); // We don't provide an error message here, as we use it to return the estimate require(execute(to, value, data, operation, gasleft())); uint256 requiredGas = startGas - gasleft(); // Convert response to string and return via error message revert(string(abi.encodePacked(requiredGas))); } /** * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature. * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract. */ function approveHash(bytes32 hashToApprove) external { require(owners[msg.sender] != address(0), "GS030"); approvedHashes[msg.sender][hashToApprove] = 1; emit ApproveHash(hashToApprove, msg.sender); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } function domainSeparator() public view returns (bytes32) { return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this)); } /// @dev Returns the bytes that are hashed to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Gas that should be used for the safe transaction. /// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash bytes. function encodeTransactionData( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes memory) { bytes32 safeTxHash = keccak256( abi.encode( SAFE_TX_TYPEHASH, to, value, keccak256(data), operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce ) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash); } /// @dev Returns hash to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Fas that should be used for the safe transaction. /// @param baseGas Gas costs for data used to trigger the safe transaction. /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash. function getTransactionHash( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes32) { return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce)); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; /// @title Executor - A contract that can execute transactions /// @author Richard Meissner - <[email protected]> contract Executor { function execute( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txGas ) internal returns (bool success) { if (operation == Enum.Operation.DelegateCall) { // solhint-disable-next-line no-inline-assembly assembly { success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0) } } else { // solhint-disable-next-line no-inline-assembly assembly { success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0) } } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/SelfAuthorized.sol"; /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract FallbackManager is SelfAuthorized { event ChangedFallbackHandler(address handler); // keccak256("fallback_manager.handler.address") bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5; function internalSetFallbackHandler(address handler) internal { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, handler) } } /// @dev Allows to add a contract to handle fallback calls. /// Only fallback calls without value and with data will be forwarded. /// This can only be done via a Safe transaction. /// @param handler contract to handle fallbacks calls. function setFallbackHandler(address handler) public authorized { internalSetFallbackHandler(handler); emit ChangedFallbackHandler(handler); } // solhint-disable-next-line payable-fallback,no-complex-fallback fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { let handler := sload(slot) if iszero(handler) { return(0, 0) } calldatacopy(0, 0, calldatasize()) // The msg.sender address is shifted to the left by 12 bytes to remove the padding // Then the address without padding is stored right after the calldata mstore(calldatasize(), shl(96, caller())) // Add 20 bytes for the address appended add the end let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0) returndatacopy(0, 0, returndatasize()) if iszero(success) { revert(0, returndatasize()) } return(0, returndatasize()) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; import "../common/SelfAuthorized.sol"; interface Guard { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkAfterExecution(bytes32 txHash, bool success) external; } /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract GuardManager is SelfAuthorized { event ChangedGuard(address guard); // keccak256("guard_manager.guard.address") bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8; /// @dev Set a guard that checks transactions before execution /// @param guard The address of the guard to be used or the 0 address to disable the guard function setGuard(address guard) external authorized { bytes32 slot = GUARD_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, guard) } emit ChangedGuard(guard); } function getGuard() internal view returns (address guard) { bytes32 slot = GUARD_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { guard := sload(slot) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; import "../common/SelfAuthorized.sol"; import "./Executor.sol"; /// @title Module Manager - A contract that manages modules that can execute transactions via this contract /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract ModuleManager is SelfAuthorized, Executor { event EnabledModule(address module); event DisabledModule(address module); event ExecutionFromModuleSuccess(address indexed module); event ExecutionFromModuleFailure(address indexed module); address internal constant SENTINEL_MODULES = address(0x1); mapping(address => address) internal modules; function setupModules(address to, bytes memory data) internal { require(modules[SENTINEL_MODULES] == address(0), "GS100"); modules[SENTINEL_MODULES] = SENTINEL_MODULES; if (to != address(0)) // Setup has to complete successfully or transaction fails. require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000"); } /// @dev Allows to add a module to the whitelist. /// This can only be done via a Safe transaction. /// @notice Enables the module `module` for the Safe. /// @param module Module to be whitelisted. function enableModule(address module) public authorized { // Module address cannot be null or sentinel. require(module != address(0) && module != SENTINEL_MODULES, "GS101"); // Module cannot be added twice. require(modules[module] == address(0), "GS102"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module); } /// @dev Allows to remove a module from the whitelist. /// This can only be done via a Safe transaction. /// @notice Disables the module `module` for the Safe. /// @param prevModule Module that pointed to the module to be removed in the linked list /// @param module Module to be removed. function disableModule(address prevModule, address module) public authorized { // Validate module address and check that it corresponds to module index. require(module != address(0) && module != SENTINEL_MODULES, "GS101"); require(modules[prevModule] == module, "GS103"); modules[prevModule] = modules[module]; modules[module] = address(0); emit DisabledModule(module); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule( address to, uint256 value, bytes memory data, Enum.Operation operation ) public virtual returns (bool success) { // Only whitelisted modules are allowed. require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104"); // Execute transaction without further confirmations. success = execute(to, value, data, operation, gasleft()); if (success) emit ExecutionFromModuleSuccess(msg.sender); else emit ExecutionFromModuleFailure(msg.sender); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModuleReturnData( address to, uint256 value, bytes memory data, Enum.Operation operation ) public returns (bool success, bytes memory returnData) { success = execTransactionFromModule(to, value, data, operation); // solhint-disable-next-line no-inline-assembly assembly { // Load free memory location let ptr := mload(0x40) // We allocate memory for the return data by setting the free memory location to // current free memory location + data size + 32 bytes for data size value mstore(0x40, add(ptr, add(returndatasize(), 0x20))) // Store the size mstore(ptr, returndatasize()) // Store the data returndatacopy(add(ptr, 0x20), 0, returndatasize()) // Point the return data to the correct memory location returnData := ptr } } /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address module) public view returns (bool) { return SENTINEL_MODULES != module && modules[module] != address(0); } /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) { // Init array with max page size array = new address[](pageSize); // Populate return array uint256 moduleCount = 0; address currentModule = modules[start]; while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) { array[moduleCount] = currentModule; currentModule = modules[currentModule]; moduleCount++; } next = currentModule; // Set correct size of returned array // solhint-disable-next-line no-inline-assembly assembly { mstore(array, moduleCount) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/SelfAuthorized.sol"; /// @title OwnerManager - Manages a set of owners and a threshold to perform actions. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract OwnerManager is SelfAuthorized { event AddedOwner(address owner); event RemovedOwner(address owner); event ChangedThreshold(uint256 threshold); address internal constant SENTINEL_OWNERS = address(0x1); mapping(address => address) internal owners; uint256 internal ownerCount; uint256 internal threshold; /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. function setupOwners(address[] memory _owners, uint256 _threshold) internal { // Threshold can only be 0 at initialization. // Check ensures that setup function can only be called once. require(threshold == 0, "GS200"); // Validate that threshold is smaller than number of added owners. require(_threshold <= _owners.length, "GS201"); // There has to be at least one Safe owner. require(_threshold >= 1, "GS202"); // Initializing Safe owners. address currentOwner = SENTINEL_OWNERS; for (uint256 i = 0; i < _owners.length; i++) { // Owner address cannot be null. address owner = _owners[i]; require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203"); // No duplicate owners allowed. require(owners[owner] == address(0), "GS204"); owners[currentOwner] = owner; currentOwner = owner; } owners[currentOwner] = SENTINEL_OWNERS; ownerCount = _owners.length; threshold = _threshold; } /// @dev Allows to add a new owner to the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`. /// @param owner New owner address. /// @param _threshold New threshold. function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized { // Owner address cannot be null, the sentinel or the Safe itself. require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203"); // No duplicate owners allowed. require(owners[owner] == address(0), "GS204"); owners[owner] = owners[SENTINEL_OWNERS]; owners[SENTINEL_OWNERS] = owner; ownerCount++; emit AddedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to remove an owner from the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`. /// @param prevOwner Owner that pointed to the owner to be removed in the linked list /// @param owner Owner address to be removed. /// @param _threshold New threshold. function removeOwner( address prevOwner, address owner, uint256 _threshold ) public authorized { // Only allow to remove an owner, if threshold can still be reached. require(ownerCount - 1 >= _threshold, "GS201"); // Validate owner address and check that it corresponds to owner index. require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203"); require(owners[prevOwner] == owner, "GS205"); owners[prevOwner] = owners[owner]; owners[owner] = address(0); ownerCount--; emit RemovedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to swap/replace an owner from the Safe with another address. /// This can only be done via a Safe transaction. /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`. /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list /// @param oldOwner Owner address to be replaced. /// @param newOwner New owner address. function swapOwner( address prevOwner, address oldOwner, address newOwner ) public authorized { // Owner address cannot be null, the sentinel or the Safe itself. require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203"); // No duplicate owners allowed. require(owners[newOwner] == address(0), "GS204"); // Validate oldOwner address and check that it corresponds to owner index. require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203"); require(owners[prevOwner] == oldOwner, "GS205"); owners[newOwner] = owners[oldOwner]; owners[prevOwner] = newOwner; owners[oldOwner] = address(0); emit RemovedOwner(oldOwner); emit AddedOwner(newOwner); } /// @dev Allows to update the number of required confirmations by Safe owners. /// This can only be done via a Safe transaction. /// @notice Changes the threshold of the Safe to `_threshold`. /// @param _threshold New threshold. function changeThreshold(uint256 _threshold) public authorized { // Validate that threshold is smaller than number of owners. require(_threshold <= ownerCount, "GS201"); // There has to be at least one Safe owner. require(_threshold >= 1, "GS202"); threshold = _threshold; emit ChangedThreshold(threshold); } function getThreshold() public view returns (uint256) { return threshold; } function isOwner(address owner) public view returns (bool) { return owner != SENTINEL_OWNERS && owners[owner] != address(0); } /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() public view returns (address[] memory) { address[] memory array = new address[](ownerCount); // populate return array uint256 index = 0; address currentOwner = owners[SENTINEL_OWNERS]; while (currentOwner != SENTINEL_OWNERS) { array[index] = currentOwner; currentOwner = owners[currentOwner]; index++; } return array; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation {Call, DelegateCall} } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments /// @author Richard Meissner - <[email protected]> contract EtherPaymentFallback { event SafeReceived(address indexed sender, uint256 value); /// @dev Fallback function accepts Ether transactions. receive() external payable { emit SafeReceived(msg.sender, msg.value); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SecuredTokenTransfer - Secure token transfer /// @author Richard Meissner - <[email protected]> contract SecuredTokenTransfer { /// @dev Transfers a token and returns if it was a success /// @param token Token that should be transferred /// @param receiver Receiver to whom the token should be transferred /// @param amount The amount of tokens that should be transferred function transferToken( address token, address receiver, uint256 amount ) internal returns (bool transferred) { // 0xa9059cbb - keccack("transfer(address,uint256)") bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount); // solhint-disable-next-line no-inline-assembly assembly { // We write the return value to scratch space. // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20) switch returndatasize() case 0 { transferred := success } case 0x20 { transferred := iszero(or(iszero(success), iszero(mload(0)))) } default { transferred := 0 } } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SelfAuthorized - authorizes current contract to perform actions /// @author Richard Meissner - <[email protected]> contract SelfAuthorized { function requireSelfCall() private view { require(msg.sender == address(this), "GS031"); } modifier authorized() { // This is a function call as it minimized the bytecode size requireSelfCall(); _; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SignatureDecoder - Decodes signatures that a encoded as bytes /// @author Richard Meissner - <[email protected]> contract SignatureDecoder { /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`. /// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access /// @param signatures concatenated rsv signatures function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns ( uint8 v, bytes32 r, bytes32 s ) { // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. // solhint-disable-next-line no-inline-assembly assembly { let signaturePos := mul(0x41, pos) r := mload(add(signatures, add(signaturePos, 0x20))) s := mload(add(signatures, add(signaturePos, 0x40))) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Singleton - Base for singleton contracts (should always be first super contract) /// This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`) /// @author Richard Meissner - <[email protected]> contract Singleton { // singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract. // It should also always be ensured that the address is stored alone (uses a full word) address private singleton; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title StorageAccessible - generic base contract that allows callers to access all internal storage. /// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol contract StorageAccessible { /** * @dev Reads `length` bytes of storage in the currents contract * @param offset - the offset in the current contract's storage in words to start reading from * @param length - the number of words (32 bytes) of data to read * @return the bytes that were read. */ function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) { bytes memory result = new bytes(length * 32); for (uint256 index = 0; index < length; index++) { // solhint-disable-next-line no-inline-assembly assembly { let word := sload(add(offset, index)) mstore(add(add(result, 0x20), mul(index, 0x20)), word) } } return result; } /** * @dev Performs a delegetecall on a targetContract in the context of self. * Internally reverts execution to avoid side effects (making it static). * * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`. * Specifically, the `returndata` after a call to this method will be: * `success:bool || response.length:uint256 || response:bytes`. * * @param targetContract Address of the contract containing the code to execute. * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments). */ function simulateAndRevert(address targetContract, bytes memory calldataPayload) external { // solhint-disable-next-line no-inline-assembly assembly { let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0) mstore(0x00, success) mstore(0x20, returndatasize()) returndatacopy(0x40, 0, returndatasize()) revert(0, add(returndatasize(), 0x40)) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /** * @title GnosisSafeMath * @dev Math operations with safety checks that revert on error * Renamed from SafeMath to GnosisSafeMath to avoid conflicts * TODO: remove once open zeppelin update to solc 0.5.0 */ library GnosisSafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; contract ISignatureValidatorConstants { // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b; } abstract contract ISignatureValidator is ISignatureValidatorConstants { /** * @dev Should return whether the signature provided is valid for the provided data * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * * MUST return the bytes4 magic value 0x20c13b0b when function passes. * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4); }