zellic-audit
Initial commit
f998fcd
raw
history blame
91.4 kB
{
"language": "Solidity",
"sources": {
"lib/openzeppelin-contracts/contracts/utils/Strings.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"lib/openzeppelin-contracts/contracts/utils/math/Math.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n"
},
"lib/oracle/contracts/ReservoirOracle.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.13;\n\n// Inspired by https://github.com/ZeframLou/trustus\nabstract contract ReservoirOracle {\n // --- Structs ---\n\n struct Message {\n bytes32 id;\n bytes payload;\n // The UNIX timestamp when the message was signed by the oracle\n uint256 timestamp;\n // ECDSA signature or EIP-2098 compact signature\n bytes signature;\n }\n\n // --- Errors ---\n\n error InvalidMessage();\n\n // --- Fields ---\n\n address public RESERVOIR_ORACLE_ADDRESS;\n\n // --- Constructor ---\n\n constructor(address reservoirOracleAddress) {\n RESERVOIR_ORACLE_ADDRESS = reservoirOracleAddress;\n }\n\n // --- Public methods ---\n\n function updateReservoirOracleAddress(address newReservoirOracleAddress)\n public\n virtual;\n\n // --- Internal methods ---\n\n function _verifyMessage(\n bytes32 id,\n uint256 validFor,\n Message memory message\n ) internal view virtual returns (bool success) {\n // Ensure the message matches the requested id\n if (id != message.id) {\n return false;\n }\n\n // Ensure the message timestamp is valid\n if (\n message.timestamp > block.timestamp ||\n message.timestamp + validFor < block.timestamp\n ) {\n return false;\n }\n\n bytes32 r;\n bytes32 s;\n uint8 v;\n\n // Extract the individual signature fields from the signature\n bytes memory signature = message.signature;\n if (signature.length == 64) {\n // EIP-2098 compact signature\n bytes32 vs;\n assembly {\n r := mload(add(signature, 0x20))\n vs := mload(add(signature, 0x40))\n s := and(\n vs,\n 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\n )\n v := add(shr(255, vs), 27)\n }\n } else if (signature.length == 65) {\n // ECDSA signature\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n } else {\n return false;\n }\n\n address signerAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19Ethereum Signed Message:\\n32\",\n // EIP-712 structured-data hash\n keccak256(\n abi.encode(\n keccak256(\n \"Message(bytes32 id,bytes payload,uint256 timestamp)\"\n ),\n message.id,\n keccak256(message.payload),\n message.timestamp\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n // Ensure the signer matches the designated oracle address\n return signerAddress == RESERVOIR_ORACLE_ADDRESS;\n }\n}\n"
},
"lib/solmate/src/auth/Owned.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Simple single owner authorization mixin.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)\nabstract contract Owned {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event OwnershipTransferred(address indexed user, address indexed newOwner);\n\n /*//////////////////////////////////////////////////////////////\n OWNERSHIP STORAGE\n //////////////////////////////////////////////////////////////*/\n\n address public owner;\n\n modifier onlyOwner() virtual {\n require(msg.sender == owner, \"UNAUTHORIZED\");\n\n _;\n }\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(address _owner) {\n owner = _owner;\n\n emit OwnershipTransferred(address(0), _owner);\n }\n\n /*//////////////////////////////////////////////////////////////\n OWNERSHIP LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function transferOwnership(address newOwner) public virtual onlyOwner {\n owner = newOwner;\n\n emit OwnershipTransferred(msg.sender, newOwner);\n }\n}\n"
},
"lib/solmate/src/tokens/ERC20.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public virtual {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n"
},
"lib/solmate/src/tokens/ERC721.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern, minimalist, and gas efficient ERC-721 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)\nabstract contract ERC721 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 indexed id);\n\n event Approval(address indexed owner, address indexed spender, uint256 indexed id);\n\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE/LOGIC\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n function tokenURI(uint256 id) public view virtual returns (string memory);\n\n /*//////////////////////////////////////////////////////////////\n ERC721 BALANCE/OWNER STORAGE\n //////////////////////////////////////////////////////////////*/\n\n mapping(uint256 => address) internal _ownerOf;\n\n mapping(address => uint256) internal _balanceOf;\n\n function ownerOf(uint256 id) public view virtual returns (address owner) {\n require((owner = _ownerOf[id]) != address(0), \"NOT_MINTED\");\n }\n\n function balanceOf(address owner) public view virtual returns (uint256) {\n require(owner != address(0), \"ZERO_ADDRESS\");\n\n return _balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC721 APPROVAL STORAGE\n //////////////////////////////////////////////////////////////*/\n\n mapping(uint256 => address) public getApproved;\n\n mapping(address => mapping(address => bool)) public isApprovedForAll;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(string memory _name, string memory _symbol) {\n name = _name;\n symbol = _symbol;\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC721 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 id) public virtual {\n address owner = _ownerOf[id];\n\n require(msg.sender == owner || isApprovedForAll[owner][msg.sender], \"NOT_AUTHORIZED\");\n\n getApproved[id] = spender;\n\n emit Approval(owner, spender, id);\n }\n\n function setApprovalForAll(address operator, bool approved) public virtual {\n isApprovedForAll[msg.sender][operator] = approved;\n\n emit ApprovalForAll(msg.sender, operator, approved);\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 id\n ) public virtual {\n require(from == _ownerOf[id], \"WRONG_FROM\");\n\n require(to != address(0), \"INVALID_RECIPIENT\");\n\n require(\n msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],\n \"NOT_AUTHORIZED\"\n );\n\n // Underflow of the sender's balance is impossible because we check for\n // ownership above and the recipient's balance can't realistically overflow.\n unchecked {\n _balanceOf[from]--;\n\n _balanceOf[to]++;\n }\n\n _ownerOf[id] = to;\n\n delete getApproved[id];\n\n emit Transfer(from, to, id);\n }\n\n function safeTransferFrom(\n address from,\n address to,\n uint256 id\n ) public virtual {\n transferFrom(from, to, id);\n\n require(\n to.code.length == 0 ||\n ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, \"\") ==\n ERC721TokenReceiver.onERC721Received.selector,\n \"UNSAFE_RECIPIENT\"\n );\n }\n\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n bytes calldata data\n ) public virtual {\n transferFrom(from, to, id);\n\n require(\n to.code.length == 0 ||\n ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) ==\n ERC721TokenReceiver.onERC721Received.selector,\n \"UNSAFE_RECIPIENT\"\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC165 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n return\n interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165\n interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721\n interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 id) internal virtual {\n require(to != address(0), \"INVALID_RECIPIENT\");\n\n require(_ownerOf[id] == address(0), \"ALREADY_MINTED\");\n\n // Counter overflow is incredibly unrealistic.\n unchecked {\n _balanceOf[to]++;\n }\n\n _ownerOf[id] = to;\n\n emit Transfer(address(0), to, id);\n }\n\n function _burn(uint256 id) internal virtual {\n address owner = _ownerOf[id];\n\n require(owner != address(0), \"NOT_MINTED\");\n\n // Ownership check above ensures no underflow.\n unchecked {\n _balanceOf[owner]--;\n }\n\n delete _ownerOf[id];\n\n delete getApproved[id];\n\n emit Transfer(owner, address(0), id);\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL SAFE MINT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _safeMint(address to, uint256 id) internal virtual {\n _mint(to, id);\n\n require(\n to.code.length == 0 ||\n ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, \"\") ==\n ERC721TokenReceiver.onERC721Received.selector,\n \"UNSAFE_RECIPIENT\"\n );\n }\n\n function _safeMint(\n address to,\n uint256 id,\n bytes memory data\n ) internal virtual {\n _mint(to, id);\n\n require(\n to.code.length == 0 ||\n ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) ==\n ERC721TokenReceiver.onERC721Received.selector,\n \"UNSAFE_RECIPIENT\"\n );\n }\n}\n\n/// @notice A generic interface for a contract which properly accepts ERC721 tokens.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)\nabstract contract ERC721TokenReceiver {\n function onERC721Received(\n address,\n address,\n uint256,\n bytes calldata\n ) external virtual returns (bytes4) {\n return ERC721TokenReceiver.onERC721Received.selector;\n }\n}\n"
},
"lib/solmate/src/utils/FixedPointMathLib.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // Divide x * y by the denominator.\n z := div(mul(x, y), denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n assembly {\n // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n revert(0, 0)\n }\n\n // If x * y modulo the denominator is strictly greater than 0,\n // 1 is added to round up the division of x * y by the denominator.\n z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}\n"
},
"lib/solmate/src/utils/MerkleProofLib.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\n/// @notice Gas optimized merkle proof verification library.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/MerkleProofLib.sol)\n/// @author Modified from Solady (https://github.com/Vectorized/solady/blob/main/src/utils/MerkleProofLib.sol)\nlibrary MerkleProofLib {\n function verify(\n bytes32[] calldata proof,\n bytes32 root,\n bytes32 leaf\n ) internal pure returns (bool isValid) {\n assembly {\n if proof.length {\n // Left shifting by 5 is like multiplying by 32.\n let end := add(proof.offset, shl(5, proof.length))\n\n // Initialize offset to the offset of the proof in calldata.\n let offset := proof.offset\n\n // Iterate over proof elements to compute root hash.\n // prettier-ignore\n for {} 1 {} {\n // Slot where the leaf should be put in scratch space. If\n // leaf > calldataload(offset): slot 32, otherwise: slot 0.\n let leafSlot := shl(5, gt(leaf, calldataload(offset)))\n\n // Store elements to hash contiguously in scratch space.\n // The xor puts calldataload(offset) in whichever slot leaf\n // is not occupying, so 0 if leafSlot is 32, and 32 otherwise.\n mstore(leafSlot, leaf)\n mstore(xor(leafSlot, 32), calldataload(offset))\n\n // Reuse leaf to store the hash to reduce stack operations.\n leaf := keccak256(0, 64) // Hash both slots of scratch space.\n\n offset := add(offset, 32) // Shift 1 word per cycle.\n\n // prettier-ignore\n if iszero(lt(offset, end)) { break }\n }\n }\n\n isValid := eq(leaf, root) // The proof is valid if the roots match.\n }\n }\n}\n"
},
"lib/solmate/src/utils/SafeTransferLib.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\n/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.\nlibrary SafeTransferLib {\n /*//////////////////////////////////////////////////////////////\n ETH OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function safeTransferETH(address to, uint256 amount) internal {\n bool success;\n\n assembly {\n // Transfer the ETH and store if it succeeded or not.\n success := call(gas(), to, amount, 0, 0, 0, 0)\n }\n\n require(success, \"ETH_TRANSFER_FAILED\");\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function safeTransferFrom(\n ERC20 token,\n address from,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), from) // Append the \"from\" argument.\n mstore(add(freeMemoryPointer, 36), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 68), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)\n )\n }\n\n require(success, \"TRANSFER_FROM_FAILED\");\n }\n\n function safeTransfer(\n ERC20 token,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n )\n }\n\n require(success, \"TRANSFER_FAILED\");\n }\n\n function safeApprove(\n ERC20 token,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n )\n }\n\n require(success, \"APPROVE_FAILED\");\n }\n}\n"
},
"src/Caviar.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\nimport \"solmate/auth/Owned.sol\";\n\nimport \"./lib/SafeERC20Namer.sol\";\nimport \"./Pair.sol\";\n\n/// @title caviar.sh\n/// @author out.eth (@outdoteth)\n/// @notice An AMM for creating and trading fractionalized NFTs.\ncontract Caviar is Owned {\n using SafeERC20Namer for address;\n\n /// @dev pairs[nft][baseToken][merkleRoot] -> pair\n mapping(address => mapping(address => mapping(bytes32 => address))) public pairs;\n\n /// @dev The stolen nft filter oracle address\n address public stolenNftFilterOracle;\n\n event SetStolenNftFilterOracle(address indexed stolenNftFilterOracle);\n event Create(address indexed nft, address indexed baseToken, bytes32 indexed merkleRoot);\n event Destroy(address indexed nft, address indexed baseToken, bytes32 indexed merkleRoot);\n\n constructor(address _stolenNftFilterOracle) Owned(msg.sender) {\n stolenNftFilterOracle = _stolenNftFilterOracle;\n }\n\n /// @notice Sets the stolen nft filter oracle address.\n /// @param _stolenNftFilterOracle The stolen nft filter oracle address.\n function setStolenNftFilterOracle(address _stolenNftFilterOracle) public onlyOwner {\n stolenNftFilterOracle = _stolenNftFilterOracle;\n emit SetStolenNftFilterOracle(_stolenNftFilterOracle);\n }\n\n /// @notice Creates a new pair.\n /// @param nft The NFT contract address.\n /// @param baseToken The base token contract address.\n /// @param merkleRoot The merkle root for the valid tokenIds.\n /// @return pair The address of the new pair.\n function create(address nft, address baseToken, bytes32 merkleRoot) public returns (Pair pair) {\n // check that the pair doesn't already exist\n require(pairs[nft][baseToken][merkleRoot] == address(0), \"Pair already exists\");\n require(nft.code.length > 0, \"Invalid NFT contract\");\n require(baseToken.code.length > 0 || baseToken == address(0), \"Invalid base token contract\");\n\n // deploy the pair\n string memory baseTokenSymbol = baseToken == address(0) ? \"ETH\" : baseToken.tokenSymbol();\n string memory nftSymbol = nft.tokenSymbol();\n string memory nftName = nft.tokenName();\n string memory pairSymbol = string.concat(nftSymbol, \":\", baseTokenSymbol);\n pair = new Pair(nft, baseToken, merkleRoot, pairSymbol, nftName, nftSymbol);\n\n // save the pair\n pairs[nft][baseToken][merkleRoot] = address(pair);\n\n emit Create(nft, baseToken, merkleRoot);\n }\n\n /// @notice Deletes the pair for the given NFT, base token, and merkle root.\n /// @param nft The NFT contract address.\n /// @param baseToken The base token contract address.\n /// @param merkleRoot The merkle root for the valid tokenIds.\n function destroy(address nft, address baseToken, bytes32 merkleRoot) public {\n // check that a pair can only destroy itself\n require(msg.sender == pairs[nft][baseToken][merkleRoot], \"Only pair can destroy itself\");\n\n // delete the pair\n delete pairs[nft][baseToken][merkleRoot];\n\n emit Destroy(nft, baseToken, merkleRoot);\n }\n}\n"
},
"src/LpToken.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\nimport \"solmate/auth/Owned.sol\";\nimport \"solmate/tokens/ERC20.sol\";\n\n/// @title LP token\n/// @author out.eth (@outdoteth)\n/// @notice LP token which is minted and burned by the Pair contract to represent liquidity in the pool.\ncontract LpToken is Owned, ERC20 {\n constructor(string memory pairSymbol)\n Owned(msg.sender)\n ERC20(string.concat(pairSymbol, \" LP token\"), string.concat(\"LP-\", pairSymbol), 18)\n {}\n\n /// @notice Mints new LP tokens to the given address.\n /// @param to The address to mint to.\n /// @param amount The amount to mint.\n function mint(address to, uint256 amount) public onlyOwner {\n _mint(to, amount);\n }\n\n /// @notice Burns LP tokens from the given address.\n /// @param from The address to burn from.\n /// @param amount The amount to burn.\n function burn(address from, uint256 amount) public onlyOwner {\n _burn(from, amount);\n }\n}\n"
},
"src/Pair.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\nimport \"solmate/tokens/ERC20.sol\";\nimport \"solmate/tokens/ERC721.sol\";\nimport \"solmate/utils/MerkleProofLib.sol\";\nimport \"solmate/utils/SafeTransferLib.sol\";\nimport \"solmate/utils/FixedPointMathLib.sol\";\nimport \"openzeppelin/utils/math/Math.sol\";\nimport \"reservoir-oracle/ReservoirOracle.sol\";\n\nimport \"./LpToken.sol\";\nimport \"./Caviar.sol\";\nimport \"./StolenNftFilterOracle.sol\";\n\n/// @title Pair\n/// @author out.eth (@outdoteth)\n/// @notice A pair of an NFT and a base token that can be used to create and trade fractionalized NFTs.\ncontract Pair is ERC20, ERC721TokenReceiver {\n using SafeTransferLib for address;\n using SafeTransferLib for ERC20;\n\n uint256 public constant CLOSE_GRACE_PERIOD = 7 days;\n uint256 private constant ONE = 1e18;\n uint256 private constant MINIMUM_LIQUIDITY = 100_000;\n\n address public immutable nft;\n address public immutable baseToken; // address(0) for ETH\n bytes32 public immutable merkleRoot;\n LpToken public immutable lpToken;\n Caviar public immutable caviar;\n uint256 public closeTimestamp;\n\n event Add(uint256 indexed baseTokenAmount, uint256 indexed fractionalTokenAmount, uint256 indexed lpTokenAmount);\n event Remove(uint256 indexed baseTokenAmount, uint256 indexed fractionalTokenAmount, uint256 indexed lpTokenAmount);\n event Buy(uint256 indexed inputAmount, uint256 indexed outputAmount);\n event Sell(uint256 indexed inputAmount, uint256 indexed outputAmount);\n event Wrap(uint256[] indexed tokenIds);\n event Unwrap(uint256[] indexed tokenIds);\n event Close(uint256 indexed closeTimestamp);\n event Withdraw(uint256 indexed tokenId);\n\n constructor(\n address _nft,\n address _baseToken,\n bytes32 _merkleRoot,\n string memory pairSymbol,\n string memory nftName,\n string memory nftSymbol\n ) ERC20(string.concat(nftName, \" fractional token\"), string.concat(\"f\", nftSymbol), 18) {\n nft = _nft;\n baseToken = _baseToken; // use address(0) for native ETH\n merkleRoot = _merkleRoot;\n lpToken = new LpToken(pairSymbol);\n caviar = Caviar(msg.sender);\n }\n\n // ************************ //\n // Core AMM logic //\n // *********************** //\n\n /// @notice Adds liquidity to the pair.\n /// @param baseTokenAmount The amount of base tokens to add.\n /// @param fractionalTokenAmount The amount of fractional tokens to add.\n /// @param minLpTokenAmount The minimum amount of LP tokens to mint.\n /// @param minPrice The minimum price that the pool should currently be at.\n /// @param maxPrice The maximum price that the pool should currently be at.\n /// @param deadline The deadline before the trade expires.\n /// @return lpTokenAmount The amount of LP tokens minted.\n function add(\n uint256 baseTokenAmount,\n uint256 fractionalTokenAmount,\n uint256 minLpTokenAmount,\n uint256 minPrice,\n uint256 maxPrice,\n uint256 deadline\n ) public payable returns (uint256 lpTokenAmount) {\n // *** Checks *** //\n\n // check that the trade has not expired\n require(deadline == 0 || deadline >= block.timestamp, \"Expired\");\n\n // check the token amount inputs are not zero\n require(baseTokenAmount > 0 && fractionalTokenAmount > 0, \"Input token amount is zero\");\n\n // check that correct eth input was sent - if the baseToken equals address(0) then native ETH is used\n require(baseToken == address(0) ? msg.value == baseTokenAmount : msg.value == 0, \"Invalid ether input\");\n\n uint256 lpTokenSupply = lpToken.totalSupply();\n\n // check that the price is within the bounds if there is liquidity in the pool\n if (lpTokenSupply != 0) {\n uint256 _price = price();\n require(_price >= minPrice && _price <= maxPrice, \"Slippage: price out of bounds\");\n }\n\n // calculate the lp token shares to mint\n lpTokenAmount = addQuote(baseTokenAmount, fractionalTokenAmount, lpTokenSupply);\n\n // check that the amount of lp tokens outputted is greater than the min amount\n require(lpTokenAmount >= minLpTokenAmount, \"Slippage: lp token amount out\");\n\n // *** Effects *** //\n\n // transfer fractional tokens in\n _transferFrom(msg.sender, address(this), fractionalTokenAmount);\n\n // *** Interactions *** //\n\n // mint lp tokens to sender\n lpToken.mint(msg.sender, lpTokenAmount);\n\n // transfer first MINIMUM_LIQUIDITY lp tokens to the owner\n if (lpTokenSupply == 0) {\n lpToken.mint(caviar.owner(), MINIMUM_LIQUIDITY);\n }\n\n // transfer base tokens in if the base token is not ETH\n if (baseToken != address(0)) {\n // transfer base tokens in\n ERC20(baseToken).safeTransferFrom(msg.sender, address(this), baseTokenAmount);\n }\n\n emit Add(baseTokenAmount, fractionalTokenAmount, lpTokenAmount);\n }\n\n /// @notice Removes liquidity from the pair.\n /// @param lpTokenAmount The amount of LP tokens to burn.\n /// @param minBaseTokenOutputAmount The minimum amount of base tokens to receive.\n /// @param minFractionalTokenOutputAmount The minimum amount of fractional tokens to receive.\n /// @param deadline The deadline before the trade expires.\n /// @return baseTokenOutputAmount The amount of base tokens received.\n /// @return fractionalTokenOutputAmount The amount of fractional tokens received.\n function remove(\n uint256 lpTokenAmount,\n uint256 minBaseTokenOutputAmount,\n uint256 minFractionalTokenOutputAmount,\n uint256 deadline\n ) public returns (uint256 baseTokenOutputAmount, uint256 fractionalTokenOutputAmount) {\n // *** Checks *** //\n\n // check that the trade has not expired\n require(deadline == 0 || deadline >= block.timestamp, \"Expired\");\n\n // calculate the output amounts\n (baseTokenOutputAmount, fractionalTokenOutputAmount) = removeQuote(lpTokenAmount);\n\n // check that the base token output amount is greater than the min amount\n require(baseTokenOutputAmount >= minBaseTokenOutputAmount, \"Slippage: base token amount out\");\n\n // check that the fractional token output amount is greater than the min amount\n require(fractionalTokenOutputAmount >= minFractionalTokenOutputAmount, \"Slippage: fractional token out\");\n\n // *** Effects *** //\n\n // transfer fractional tokens to sender\n _transferFrom(address(this), msg.sender, fractionalTokenOutputAmount);\n\n // *** Interactions *** //\n\n // burn lp tokens from sender\n lpToken.burn(msg.sender, lpTokenAmount);\n\n if (baseToken == address(0)) {\n // if base token is native ETH then send ether to sender\n msg.sender.safeTransferETH(baseTokenOutputAmount);\n } else {\n // transfer base tokens to sender\n ERC20(baseToken).safeTransfer(msg.sender, baseTokenOutputAmount);\n }\n\n emit Remove(baseTokenOutputAmount, fractionalTokenOutputAmount, lpTokenAmount);\n }\n\n /// @notice Buys fractional tokens from the pair.\n /// @param outputAmount The amount of fractional tokens to buy.\n /// @param maxInputAmount The maximum amount of base tokens to spend.\n /// @param deadline The deadline before the trade expires.\n /// @return inputAmount The amount of base tokens spent.\n function buy(uint256 outputAmount, uint256 maxInputAmount, uint256 deadline)\n public\n payable\n returns (uint256 inputAmount)\n {\n // *** Checks *** //\n\n // check that the trade has not expired\n require(deadline == 0 || deadline >= block.timestamp, \"Expired\");\n\n // check that correct eth input was sent - if the baseToken equals address(0) then native ETH is used\n require(baseToken == address(0) ? msg.value == maxInputAmount : msg.value == 0, \"Invalid ether input\");\n\n // calculate required input amount using xyk invariant\n inputAmount = buyQuote(outputAmount);\n\n // check that the required amount of base tokens is less than the max amount\n require(inputAmount <= maxInputAmount, \"Slippage: amount in\");\n\n // *** Effects *** //\n\n // transfer fractional tokens to sender\n _transferFrom(address(this), msg.sender, outputAmount);\n\n // *** Interactions *** //\n\n if (baseToken == address(0)) {\n // refund surplus eth\n uint256 refundAmount = maxInputAmount - inputAmount;\n if (refundAmount > 0) msg.sender.safeTransferETH(refundAmount);\n } else {\n // transfer base tokens in\n ERC20(baseToken).safeTransferFrom(msg.sender, address(this), inputAmount);\n }\n\n emit Buy(inputAmount, outputAmount);\n }\n\n /// @notice Sells fractional tokens to the pair.\n /// @param inputAmount The amount of fractional tokens to sell.\n /// @param deadline The deadline before the trade expires.\n /// @param minOutputAmount The minimum amount of base tokens to receive.\n /// @return outputAmount The amount of base tokens received.\n function sell(uint256 inputAmount, uint256 minOutputAmount, uint256 deadline)\n public\n returns (uint256 outputAmount)\n {\n // *** Checks *** //\n\n // check that the trade has not expired\n require(deadline == 0 || deadline >= block.timestamp, \"Expired\");\n\n // calculate output amount using xyk invariant\n outputAmount = sellQuote(inputAmount);\n\n // check that the outputted amount of fractional tokens is greater than the min amount\n require(outputAmount >= minOutputAmount, \"Slippage: amount out\");\n\n // *** Effects *** //\n\n // transfer fractional tokens from sender\n _transferFrom(msg.sender, address(this), inputAmount);\n\n // *** Interactions *** //\n\n if (baseToken == address(0)) {\n // transfer ether out\n msg.sender.safeTransferETH(outputAmount);\n } else {\n // transfer base tokens out\n ERC20(baseToken).safeTransfer(msg.sender, outputAmount);\n }\n\n emit Sell(inputAmount, outputAmount);\n }\n\n // ******************** //\n // Wrap logic //\n // ******************** //\n\n /// @notice Wraps NFTs into fractional tokens.\n /// @param tokenIds The ids of the NFTs to wrap.\n /// @param proofs The merkle proofs for the NFTs proving that they can be used in the pair.\n /// @return fractionalTokenAmount The amount of fractional tokens minted.\n function wrap(uint256[] calldata tokenIds, bytes32[][] calldata proofs, ReservoirOracle.Message[] calldata messages)\n public\n returns (uint256 fractionalTokenAmount)\n {\n // *** Checks *** //\n\n // check that wrapping is not closed\n require(closeTimestamp == 0, \"Wrap: closed\");\n\n // check the tokens exist in the merkle root\n _validateTokenIds(tokenIds, proofs);\n\n // check that the tokens are not stolen with reservoir oracle\n _validateTokensAreNotStolen(tokenIds, messages);\n\n // *** Effects *** //\n\n // mint fractional tokens to sender\n fractionalTokenAmount = tokenIds.length * ONE;\n _mint(msg.sender, fractionalTokenAmount);\n\n // *** Interactions *** //\n\n // transfer nfts from sender\n for (uint256 i = 0; i < tokenIds.length;) {\n ERC721(nft).safeTransferFrom(msg.sender, address(this), tokenIds[i]);\n\n unchecked {\n i++;\n }\n }\n\n emit Wrap(tokenIds);\n }\n\n /// @notice Unwraps fractional tokens into NFTs.\n /// @param tokenIds The ids of the NFTs to unwrap.\n /// @param withFee Whether to pay a fee for unwrapping or not.\n /// @return fractionalTokenAmount The amount of fractional tokens burned.\n function unwrap(uint256[] calldata tokenIds, bool withFee) public returns (uint256 fractionalTokenAmount) {\n // *** Effects *** //\n\n // burn fractional tokens from sender\n fractionalTokenAmount = tokenIds.length * ONE;\n _burn(msg.sender, fractionalTokenAmount);\n\n // Take the fee if withFee is true\n if (withFee) {\n // calculate fee\n uint256 fee = fractionalTokenAmount * 3 / 1000;\n\n // transfer fee from sender\n _transferFrom(msg.sender, address(this), fee);\n fractionalTokenAmount += fee;\n }\n\n // transfer nfts to sender\n for (uint256 i = 0; i < tokenIds.length;) {\n ERC721(nft).safeTransferFrom(address(this), msg.sender, tokenIds[i]);\n\n unchecked {\n i++;\n }\n }\n\n emit Unwrap(tokenIds);\n }\n\n // *********************** //\n // NFT AMM logic //\n // *********************** //\n\n /// @notice nftAdd Adds liquidity to the pair using NFTs.\n /// @param baseTokenAmount The amount of base tokens to add.\n /// @param tokenIds The ids of the NFTs to add.\n /// @param minLpTokenAmount The minimum amount of lp tokens to receive.\n /// @param minPrice The minimum price of the pair.\n /// @param maxPrice The maximum price of the pair.\n /// @param deadline The deadline for the transaction.\n /// @param proofs The merkle proofs for the NFTs.\n /// @return lpTokenAmount The amount of lp tokens minted.\n function nftAdd(\n uint256 baseTokenAmount,\n uint256[] calldata tokenIds,\n uint256 minLpTokenAmount,\n uint256 minPrice,\n uint256 maxPrice,\n uint256 deadline,\n bytes32[][] calldata proofs,\n ReservoirOracle.Message[] calldata messages\n ) public payable returns (uint256 lpTokenAmount) {\n // wrap the incoming NFTs into fractional tokens\n uint256 fractionalTokenAmount = wrap(tokenIds, proofs, messages);\n\n // add liquidity using the fractional tokens and base tokens\n lpTokenAmount = add(baseTokenAmount, fractionalTokenAmount, minLpTokenAmount, minPrice, maxPrice, deadline);\n }\n\n /// @notice Removes liquidity from the pair using NFTs.\n /// @param lpTokenAmount The amount of lp tokens to remove.\n /// @param minBaseTokenOutputAmount The minimum amount of base tokens to receive.\n /// @param deadline The deadline before the trade expires.\n /// @param tokenIds The ids of the NFTs to remove.\n /// @param withFee Whether to pay a fee for unwrapping or not.\n /// @return baseTokenOutputAmount The amount of base tokens received.\n /// @return fractionalTokenOutputAmount The amount of fractional tokens received.\n function nftRemove(\n uint256 lpTokenAmount,\n uint256 minBaseTokenOutputAmount,\n uint256 deadline,\n uint256[] calldata tokenIds,\n bool withFee\n ) public returns (uint256 baseTokenOutputAmount, uint256 fractionalTokenOutputAmount) {\n // remove liquidity and send fractional tokens and base tokens to sender\n (baseTokenOutputAmount, fractionalTokenOutputAmount) =\n remove(lpTokenAmount, minBaseTokenOutputAmount, tokenIds.length * ONE, deadline);\n\n // unwrap the fractional tokens into NFTs and send to sender\n unwrap(tokenIds, withFee);\n }\n\n /// @notice Buys NFTs from the pair using base tokens.\n /// @param tokenIds The ids of the NFTs to buy.\n /// @param maxInputAmount The maximum amount of base tokens to spend.\n /// @param deadline The deadline before the trade expires.\n /// @return inputAmount The amount of base tokens spent.\n function nftBuy(uint256[] calldata tokenIds, uint256 maxInputAmount, uint256 deadline)\n public\n payable\n returns (uint256 inputAmount)\n {\n // buy fractional tokens using base tokens\n inputAmount = buy(tokenIds.length * ONE, maxInputAmount, deadline);\n\n // unwrap the fractional tokens into NFTs and send to sender\n unwrap(tokenIds, false);\n }\n\n /// @notice Sells NFTs to the pair for base tokens.\n /// @param tokenIds The ids of the NFTs to sell.\n /// @param minOutputAmount The minimum amount of base tokens to receive.\n /// @param deadline The deadline before the trade expires.\n /// @param proofs The merkle proofs for the NFTs.\n /// @return outputAmount The amount of base tokens received.\n function nftSell(\n uint256[] calldata tokenIds,\n uint256 minOutputAmount,\n uint256 deadline,\n bytes32[][] calldata proofs,\n ReservoirOracle.Message[] calldata messages\n ) public returns (uint256 outputAmount) {\n // wrap the incoming NFTs into fractional tokens\n uint256 inputAmount = wrap(tokenIds, proofs, messages);\n\n // sell fractional tokens for base tokens\n outputAmount = sell(inputAmount, minOutputAmount, deadline);\n }\n\n // ****************************** //\n // Emergency exit logic //\n // ****************************** //\n\n /// @notice Closes the pair to new wraps.\n /// @dev Can only be called by the caviar owner. This is used as an emergency exit in case\n /// the caviar owner suspects that the pair has been compromised.\n function close() public {\n // check that the sender is the caviar owner\n require(caviar.owner() == msg.sender, \"Close: not owner\");\n\n // set the close timestamp with a grace period\n closeTimestamp = block.timestamp + CLOSE_GRACE_PERIOD;\n\n // remove the pair from the Caviar contract\n caviar.destroy(nft, baseToken, merkleRoot);\n\n emit Close(closeTimestamp);\n }\n\n /// @notice Withdraws a particular NFT from the pair.\n /// @dev Can only be called by the caviar owner after the close grace period has passed. This\n /// is used to auction off the NFTs in the pair in case NFTs get stuck due to liquidity\n /// imbalances. Proceeds from the auction should be distributed pro rata to fractional\n /// token holders. See documentation for more details.\n function withdraw(uint256 tokenId) public {\n // check that the sender is the caviar owner\n require(caviar.owner() == msg.sender, \"Withdraw: not owner\");\n\n // check that the close period has been set\n require(closeTimestamp != 0, \"Withdraw not initiated\");\n\n // check that the close grace period has passed\n require(block.timestamp >= closeTimestamp, \"Not withdrawable yet\");\n\n // transfer the nft to the caviar owner\n ERC721(nft).safeTransferFrom(address(this), msg.sender, tokenId);\n\n emit Withdraw(tokenId);\n }\n\n // ***************** //\n // Getters //\n // ***************** //\n\n function baseTokenReserves() public view returns (uint256) {\n return _baseTokenReserves();\n }\n\n function fractionalTokenReserves() public view returns (uint256) {\n return balanceOf[address(this)];\n }\n\n /// @notice The current price of one fractional token in base tokens with 18 decimals of precision.\n /// @dev Calculated by dividing the base token reserves by the fractional token reserves.\n /// @return price The price of one fractional token in base tokens * 1e18.\n function price() public view returns (uint256) {\n uint256 exponent = baseToken == address(0) ? 18 : (36 - ERC20(baseToken).decimals());\n return (_baseTokenReserves() * 10 ** exponent) / fractionalTokenReserves();\n }\n\n /// @notice The amount of base tokens required to buy a given amount of fractional tokens.\n /// @dev Calculated using the xyk invariant and a 30bps fee.\n /// @param outputAmount The amount of fractional tokens to buy.\n /// @return inputAmount The amount of base tokens required.\n function buyQuote(uint256 outputAmount) public view returns (uint256) {\n return FixedPointMathLib.mulDivUp(\n outputAmount * 1000, baseTokenReserves(), (fractionalTokenReserves() - outputAmount) * 990\n );\n }\n\n /// @notice The amount of base tokens received for selling a given amount of fractional tokens.\n /// @dev Calculated using the xyk invariant and a 30bps fee.\n /// @param inputAmount The amount of fractional tokens to sell.\n /// @return outputAmount The amount of base tokens received.\n function sellQuote(uint256 inputAmount) public view returns (uint256) {\n uint256 inputAmountWithFee = inputAmount * 990;\n return (inputAmountWithFee * baseTokenReserves()) / ((fractionalTokenReserves() * 1000) + inputAmountWithFee);\n }\n\n /// @notice The amount of lp tokens received for adding a given amount of base tokens and fractional tokens.\n /// @dev Calculated as a share of existing deposits. If there are no existing deposits, then initializes to\n /// sqrt(baseTokenAmount * fractionalTokenAmount).\n /// @param baseTokenAmount The amount of base tokens to add.\n /// @param fractionalTokenAmount The amount of fractional tokens to add.\n /// @return lpTokenAmount The amount of lp tokens received.\n function addQuote(uint256 baseTokenAmount, uint256 fractionalTokenAmount, uint256 lpTokenSupply)\n public\n view\n returns (uint256)\n {\n if (lpTokenSupply != 0) {\n // calculate amount of lp tokens as a fraction of existing reserves\n uint256 baseTokenShare = (baseTokenAmount * lpTokenSupply) / baseTokenReserves();\n uint256 fractionalTokenShare = (fractionalTokenAmount * lpTokenSupply) / fractionalTokenReserves();\n return Math.min(baseTokenShare, fractionalTokenShare);\n } else {\n // if there is no liquidity then init\n return Math.sqrt(baseTokenAmount * fractionalTokenAmount) - MINIMUM_LIQUIDITY;\n }\n }\n\n /// @notice The amount of base tokens and fractional tokens received for burning a given amount of lp tokens.\n /// @dev Calculated as a share of existing deposits.\n /// @param lpTokenAmount The amount of lp tokens to burn.\n /// @return baseTokenAmount The amount of base tokens received.\n /// @return fractionalTokenAmount The amount of fractional tokens received.\n function removeQuote(uint256 lpTokenAmount) public view returns (uint256, uint256) {\n uint256 lpTokenSupply = lpToken.totalSupply();\n uint256 baseTokenOutputAmount = (baseTokenReserves() * lpTokenAmount) / lpTokenSupply;\n uint256 fractionalTokenOutputAmount = (fractionalTokenReserves() * lpTokenAmount) / lpTokenSupply;\n uint256 upperFractionalTokenOutputAmount = (fractionalTokenReserves() * (lpTokenAmount + 1)) / lpTokenSupply;\n\n if (\n fractionalTokenOutputAmount % 1e18 != 0\n && upperFractionalTokenOutputAmount - fractionalTokenOutputAmount <= 1000 && lpTokenSupply > 1e15\n ) {\n fractionalTokenOutputAmount = upperFractionalTokenOutputAmount;\n }\n\n return (baseTokenOutputAmount, fractionalTokenOutputAmount);\n }\n\n // ************************ //\n // Internal utils //\n // ************************ //\n\n function _transferFrom(address from, address to, uint256 amount) internal returns (bool) {\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n function _validateTokensAreNotStolen(uint256[] calldata tokenIds, ReservoirOracle.Message[] calldata messages)\n internal\n view\n {\n address stolenNftFilterAddress = caviar.stolenNftFilterOracle();\n\n // if filter address is not set then no need to check if nfts are stolen\n if (stolenNftFilterAddress == address(0)) return;\n\n // validate that nfts are not stolen\n StolenNftFilterOracle(stolenNftFilterAddress).validateTokensAreNotStolen(nft, tokenIds, messages);\n }\n\n /// @dev Validates that the given tokenIds are valid for the contract's merkle root. Reverts\n /// if any of the tokenId proofs are invalid.\n function _validateTokenIds(uint256[] calldata tokenIds, bytes32[][] calldata proofs) internal view {\n // if merkle root is not set then all tokens are valid\n if (merkleRoot == bytes32(0)) return;\n\n // validate merkle proofs against merkle root\n for (uint256 i = 0; i < tokenIds.length;) {\n bool isValid = MerkleProofLib.verify(\n proofs[i],\n merkleRoot,\n // double hash to prevent second preimage attacks\n keccak256(bytes.concat(keccak256(abi.encode(tokenIds[i]))))\n );\n\n require(isValid, \"Invalid merkle proof\");\n\n unchecked {\n i++;\n }\n }\n }\n\n /// @dev Returns the current base token reserves. If the base token is ETH then it ignores\n /// the msg.value that is being sent in the current call context - this is to ensure the\n /// xyk math is correct in the buy() and add() functions.\n function _baseTokenReserves() internal view returns (uint256) {\n return baseToken == address(0)\n ? address(this).balance - msg.value // subtract the msg.value if the base token is ETH\n : ERC20(baseToken).balanceOf(address(this));\n }\n}\n"
},
"src/StolenNftFilterOracle.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\nimport \"solmate/auth/Owned.sol\";\nimport \"reservoir-oracle/ReservoirOracle.sol\";\n\n/// @title StolenNftFilterOracle\n/// @author out.eth (@outdoteth)\n/// @notice A contract to check that a set of NFTs are not stolen.\ncontract StolenNftFilterOracle is ReservoirOracle, Owned {\n bytes32 private constant TOKEN_TYPE_HASH = keccak256(\"Token(address contract,uint256 tokenId)\");\n uint256 public cooldownPeriod = 0;\n uint256 public validFor = 60 minutes;\n\n constructor() Owned(msg.sender) ReservoirOracle(0xAeB1D03929bF87F69888f381e73FBf75753d75AF) {}\n\n /// @notice Sets the cooldown period.\n /// @param _cooldownPeriod The cooldown period.\n function setCooldownPeriod(uint256 _cooldownPeriod) public onlyOwner {\n cooldownPeriod = _cooldownPeriod;\n }\n\n /// @notice Sets the valid for period.\n /// @param _validFor The valid for period.\n function setValidFor(uint256 _validFor) public onlyOwner {\n validFor = _validFor;\n }\n\n function updateReservoirOracleAddress(address newReservoirOracleAddress) public override onlyOwner {\n RESERVOIR_ORACLE_ADDRESS = newReservoirOracleAddress;\n }\n\n /// @notice Checks that a set of NFTs are not stolen.\n /// @param tokenAddress The address of the NFT contract.\n /// @param tokenIds The ids of the NFTs.\n /// @param messages The messages signed by the reservoir oracle.\n function validateTokensAreNotStolen(address tokenAddress, uint256[] calldata tokenIds, Message[] calldata messages)\n public\n view\n {\n for (uint256 i = 0; i < tokenIds.length; i++) {\n Message calldata message = messages[i];\n\n // check that the signer is correct and message id matches token id + token address\n bytes32 expectedMessageId = keccak256(abi.encode(TOKEN_TYPE_HASH, tokenAddress, tokenIds[i]));\n require(_verifyMessage(expectedMessageId, validFor, message), \"Message has invalid signature\");\n\n (bool isFlagged, uint256 lastTransferTime) = abi.decode(message.payload, (bool, uint256));\n\n // check that the NFT is not stolen\n require(!isFlagged, \"NFT is flagged as suspicious\");\n\n // check that the NFT was not transferred too recently\n require(lastTransferTime + cooldownPeriod < block.timestamp, \"NFT was transferred too recently\");\n }\n }\n}\n"
},
"src/lib/SafeERC20Namer.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.17;\n\nimport \"openzeppelin/utils/Strings.sol\";\n\n// modified from https://github.com/Uniswap/solidity-lib/blob/master/contracts/libraries/SafeERC20Namer.sol\n// produces token descriptors from inconsistent or absent ERC20 symbol implementations that can return string or bytes32\n// this library will always produce a string symbol to represent the token\nlibrary SafeERC20Namer {\n function bytes32ToString(bytes32 x) private pure returns (string memory) {\n bytes memory bytesString = new bytes(32);\n uint256 charCount = 0;\n for (uint256 j = 0; j < 32; j++) {\n bytes1 char = x[j];\n if (char != 0) {\n bytesString[charCount] = char;\n charCount++;\n }\n }\n\n bytes memory bytesStringTrimmed = new bytes(charCount);\n for (uint256 j = 0; j < charCount; j++) {\n bytesStringTrimmed[j] = bytesString[j];\n }\n\n return string(bytesStringTrimmed);\n }\n\n // uses a heuristic to produce a token name from the address\n // the heuristic returns the full hex of the address string\n function addressToName(address token) private pure returns (string memory) {\n return Strings.toHexString(uint160(token));\n }\n\n // uses a heuristic to produce a token symbol from the address\n // the heuristic returns the first 4 hex of the address string\n function addressToSymbol(address token) private pure returns (string memory) {\n return Strings.toHexString(uint160(token) >> (160 - 4 * 4));\n }\n\n // calls an external view token contract method that returns a symbol or name, and parses the output into a string\n function callAndParseStringReturn(address token, bytes4 selector) private view returns (string memory) {\n (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector));\n // if not implemented, or returns empty data, return empty string\n if (!success || data.length == 0) {\n return \"\";\n }\n // bytes32 data always has length 32\n if (data.length == 32) {\n bytes32 decoded = abi.decode(data, (bytes32));\n return bytes32ToString(decoded);\n } else if (data.length > 64) {\n return abi.decode(data, (string));\n }\n return \"\";\n }\n\n // attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address\n function tokenSymbol(address token) internal view returns (string memory) {\n // 0x95d89b41 = bytes4(keccak256(\"symbol()\"))\n string memory symbol = callAndParseStringReturn(token, 0x95d89b41);\n if (bytes(symbol).length == 0) {\n // fallback to 6 uppercase hex of address\n return addressToSymbol(token);\n }\n return symbol;\n }\n\n // attempts to extract the token name. if it does not implement name, returns a name derived from the address\n function tokenName(address token) internal view returns (string memory) {\n // 0x06fdde03 = bytes4(keccak256(\"name()\"))\n string memory name = callAndParseStringReturn(token, 0x06fdde03);\n if (bytes(name).length == 0) {\n // fallback to full hex of address\n return addressToName(token);\n }\n\n return name;\n }\n}\n"
}
},
"settings": {
"remappings": [
"@manifoldxyz/libraries-solidity/=lib/royalty-registry-solidity/lib/libraries-solidity/",
"@openzeppelin/contracts-upgradeable/=lib/royalty-registry-solidity/lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/royalty-registry-solidity/lib/openzeppelin-contracts/contracts/",
"ERC721A/=lib/ERC721A/contracts/",
"create2-helpers/=lib/royalty-registry-solidity/lib/create2-helpers/src/",
"create2-scripts/=lib/royalty-registry-solidity/lib/create2-helpers/script/",
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"libraries-solidity/=lib/royalty-registry-solidity/lib/libraries-solidity/contracts/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/",
"oracle/=lib/oracle/contracts/",
"reservoir-oracle/=lib/oracle/contracts/",
"royalty-registry-solidity/=lib/royalty-registry-solidity/contracts/",
"solmate/=lib/solmate/src/"
],
"optimizer": {
"enabled": true,
"runs": 100
},
"metadata": {
"bytecodeHash": "ipfs"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "london",
"libraries": {}
}
}