{ "language": "Solidity", "sources": { "contracts/misc/AutoCompoundApe.sol": { "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.8.10;\n\nimport \"../dependencies/openzeppelin/upgradeability/Initializable.sol\";\nimport \"../dependencies/openzeppelin/upgradeability/OwnableUpgradeable.sol\";\nimport {IERC20} from \"../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {SafeERC20} from \"../dependencies/openzeppelin/contracts/SafeERC20.sol\";\nimport {ApeCoinStaking} from \"../dependencies/yoga-labs/ApeCoinStaking.sol\";\nimport {IAutoCompoundApe} from \"../interfaces/IAutoCompoundApe.sol\";\nimport {CApe} from \"./CApe.sol\";\n\ncontract AutoCompoundApe is\n Initializable,\n OwnableUpgradeable,\n CApe,\n IAutoCompoundApe\n{\n using SafeERC20 for IERC20;\n\n /// @notice ApeCoin single pool POOL_ID for ApeCoinStaking\n uint256 public constant APE_COIN_POOL_ID = 0;\n /// @notice Minimal ApeCoin amount to deposit ape to ApeCoinStaking\n uint256 public constant MIN_OPERATION_AMOUNT = 100 * 1e18;\n /// @notice Minimal liquidity the pool should have\n uint256 public constant MINIMUM_LIQUIDITY = 10**15;\n\n ApeCoinStaking public immutable apeStaking;\n IERC20 public immutable apeCoin;\n uint256 public bufferBalance;\n\n constructor(address _apeCoin, address _apeStaking) {\n apeStaking = ApeCoinStaking(_apeStaking);\n apeCoin = IERC20(_apeCoin);\n }\n\n function initialize() public initializer {\n __Ownable_init();\n __Pausable_init();\n apeCoin.safeApprove(address(apeStaking), type(uint256).max);\n }\n\n /// @inheritdoc IAutoCompoundApe\n function deposit(address onBehalf, uint256 amount) external override {\n require(amount > 0, \"zero amount\");\n uint256 amountShare = getShareByPooledApe(amount);\n if (amountShare == 0) {\n amountShare = amount;\n // permanently lock the first MINIMUM_LIQUIDITY tokens to prevent getPooledApeByShares return 0\n _mint(address(1), MINIMUM_LIQUIDITY);\n amountShare = amountShare - MINIMUM_LIQUIDITY;\n }\n _mint(onBehalf, amountShare);\n\n _transferTokenIn(msg.sender, amount);\n _harvest();\n _compound();\n\n emit Transfer(address(0), onBehalf, amount);\n emit Deposit(msg.sender, onBehalf, amount, amountShare);\n }\n\n /// @inheritdoc IAutoCompoundApe\n function withdraw(uint256 amount) external override {\n require(amount > 0, \"zero amount\");\n\n uint256 amountShare = getShareByPooledApe(amount);\n _burn(msg.sender, amountShare);\n\n _harvest();\n uint256 _bufferBalance = bufferBalance;\n if (amount > _bufferBalance) {\n _withdrawFromApeCoinStaking(amount - _bufferBalance);\n }\n _transferTokenOut(msg.sender, amount);\n\n _compound();\n\n emit Transfer(msg.sender, address(0), amount);\n emit Redeem(msg.sender, amount, amountShare);\n }\n\n /// @inheritdoc IAutoCompoundApe\n function harvestAndCompound() external {\n _harvest();\n _compound();\n }\n\n function _getTotalPooledApeBalance()\n internal\n view\n override\n returns (uint256)\n {\n (uint256 stakedAmount, ) = apeStaking.addressPosition(address(this));\n uint256 rewardAmount = apeStaking.pendingRewards(\n APE_COIN_POOL_ID,\n address(this),\n 0\n );\n return stakedAmount + rewardAmount + bufferBalance;\n }\n\n function _withdrawFromApeCoinStaking(uint256 amount) internal {\n uint256 balanceBefore = apeCoin.balanceOf(address(this));\n apeStaking.withdrawSelfApeCoin(amount);\n uint256 balanceAfter = apeCoin.balanceOf(address(this));\n uint256 realWithdraw = balanceAfter - balanceBefore;\n bufferBalance += realWithdraw;\n }\n\n function _transferTokenIn(address from, uint256 amount) internal {\n apeCoin.safeTransferFrom(from, address(this), amount);\n bufferBalance += amount;\n }\n\n function _transferTokenOut(address to, uint256 amount) internal {\n apeCoin.safeTransfer(to, amount);\n bufferBalance -= amount;\n }\n\n function _compound() internal {\n uint256 _bufferBalance = bufferBalance;\n if (_bufferBalance >= MIN_OPERATION_AMOUNT) {\n apeStaking.depositSelfApeCoin(_bufferBalance);\n bufferBalance = 0;\n }\n }\n\n function _harvest() internal {\n uint256 rewardAmount = apeStaking.pendingRewards(\n APE_COIN_POOL_ID,\n address(this),\n 0\n );\n if (rewardAmount > 0) {\n apeStaking.claimSelfApeCoin();\n bufferBalance += rewardAmount;\n }\n }\n\n function rescueERC20(\n address token,\n address to,\n uint256 amount\n ) external onlyOwner {\n if (token == address(apeCoin)) {\n require(\n bufferBalance <= (apeCoin.balanceOf(address(this)) - amount),\n \"balance below backed balance\"\n );\n }\n IERC20(token).safeTransfer(to, amount);\n emit RescueERC20(token, to, amount);\n }\n}\n" }, "contracts/misc/CApe.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\nimport \"../dependencies/openzeppelin/upgradeability/ContextUpgradeable.sol\";\nimport \"../dependencies/openzeppelin/upgradeability/PausableUpgradeable.sol\";\nimport \"../dependencies/openzeppelin/contracts//Context.sol\";\nimport \"../dependencies/openzeppelin/contracts//IERC20.sol\";\nimport \"../dependencies/openzeppelin/contracts//SafeMath.sol\";\nimport \"../dependencies/openzeppelin/contracts//Address.sol\";\nimport \"../dependencies/openzeppelin/contracts//Pausable.sol\";\nimport {ICApe} from \"../interfaces/ICApe.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n */\nabstract contract CApe is ContextUpgradeable, ICApe, PausableUpgradeable {\n using SafeMath for uint256;\n using Address for address;\n\n mapping(address => uint256) private shares;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalShare;\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public pure returns (string memory) {\n return \"ParaSpace Compound APE\";\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public pure returns (string memory) {\n return \"cAPE\";\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n */\n function decimals() public pure returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _getTotalPooledApeBalance();\n }\n\n /**\n * @return the entire amount of APE controlled by the protocol.\n *\n * @dev The sum of all APE balances in the protocol, equals to the total supply of PsAPE.\n */\n function getTotalPooledApeBalance() public view returns (uint256) {\n return _getTotalPooledApeBalance();\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account)\n public\n view\n virtual\n override\n returns (uint256)\n {\n return getPooledApeByShares(_sharesOf(account));\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `recipient` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address recipient, uint256 amount)\n public\n virtual\n override\n returns (bool)\n {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender)\n public\n view\n virtual\n override\n returns (uint256)\n {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount)\n public\n virtual\n override\n returns (bool)\n {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20};\n *\n * Requirements:\n * - `sender` and `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n * - the caller must have allowance for ``sender``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) public virtual override returns (bool) {\n _transfer(sender, recipient, amount);\n if (sender != _msgSender()) {\n _approve(\n sender,\n _msgSender(),\n _allowances[sender][_msgSender()].sub(\n amount,\n \"TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE\"\n )\n );\n }\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue)\n public\n virtual\n returns (bool)\n {\n _approve(\n _msgSender(),\n spender,\n _allowances[_msgSender()][spender].add(addedValue)\n );\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue)\n public\n virtual\n returns (bool)\n {\n _approve(\n _msgSender(),\n spender,\n _allowances[_msgSender()][spender].sub(\n subtractedValue,\n \"DECREASED_ALLOWANCE_BELOW_ZERO\"\n )\n );\n return true;\n }\n\n /**\n * @return the total amount of shares in existence.\n *\n * @dev The sum of all accounts' shares can be an arbitrary number, therefore\n * it is necessary to store it in order to calculate each account's relative share.\n */\n function getTotalShares() public view returns (uint256) {\n return _getTotalShares();\n }\n\n /**\n * @return the amount of shares owned by `_account`.\n */\n function sharesOf(address _account) public view returns (uint256) {\n return _sharesOf(_account);\n }\n\n /**\n * @return the amount of shares that corresponds to `amount` protocol-controlled Ape.\n */\n function getShareByPooledApe(uint256 amount) public view returns (uint256) {\n uint256 totalPooledApe = _getTotalPooledApeBalance();\n if (totalPooledApe == 0) {\n return 0;\n } else {\n return (amount * _getTotalShares()) / totalPooledApe;\n }\n }\n\n /**\n * @return the amount of ApeCoin that corresponds to `_sharesAmount` token shares.\n */\n function getPooledApeByShares(uint256 sharesAmount)\n public\n view\n returns (uint256)\n {\n uint256 totalShares = _getTotalShares();\n if (totalShares == 0) {\n return 0;\n } else {\n return\n sharesAmount.mul(_getTotalPooledApeBalance()).div(totalShares);\n }\n }\n\n /**\n * @return the total amount (in wei) of APE controlled by the protocol.\n * @dev This is used for calculating tokens from shares and vice versa.\n * @dev This function is required to be implemented in a derived contract.\n */\n function _getTotalPooledApeBalance()\n internal\n view\n virtual\n returns (uint256);\n\n /**\n * @dev Moves tokens `amount` from `sender` to `recipient`.\n *\n * This is internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `sender` cannot be the zero address.\n * - `recipient` cannot be the zero address.\n * - `sender` must have a balance of at least `amount`.\n */\n function _transfer(\n address sender,\n address recipient,\n uint256 amount\n ) internal virtual {\n require(sender != address(0), \"transfer from the zero address\");\n require(recipient != address(0), \"transfer to the zero address\");\n\n uint256 _sharesToTransfer = getShareByPooledApe(amount);\n _transferShares(sender, recipient, _sharesToTransfer);\n emit Transfer(sender, recipient, amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.\n *\n * This is internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual whenNotPaused {\n require(owner != address(0), \"approve from the zero address\");\n require(spender != address(0), \"approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @return the total amount of shares in existence.\n */\n function _getTotalShares() internal view returns (uint256) {\n return _totalShare;\n }\n\n /**\n * @return the amount of shares owned by `_account`.\n */\n function _sharesOf(address _account) internal view returns (uint256) {\n return shares[_account];\n }\n\n /**\n * @notice Moves `_sharesAmount` shares from `_sender` to `_recipient`.\n *\n * Requirements:\n *\n * - `_sender` cannot be the zero address.\n * - `_recipient` cannot be the zero address.\n * - `_sender` must hold at least `_sharesAmount` shares.\n * - the contract must not be paused.\n */\n function _transferShares(\n address _sender,\n address _recipient,\n uint256 _sharesAmount\n ) internal whenNotPaused {\n shares[_sender] = shares[_sender].sub(\n _sharesAmount,\n \"transfer amount exceeds balance\"\n );\n shares[_recipient] = shares[_recipient].add(_sharesAmount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements\n *\n * - `to` cannot be the zero address.\n */\n function _mint(address account, uint256 sharesAmount)\n internal\n virtual\n whenNotPaused\n {\n require(account != address(0), \"mint to the zero address\");\n\n _totalShare = _totalShare.add(sharesAmount);\n shares[account] = shares[account].add(sharesAmount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 sharesAmount)\n internal\n virtual\n whenNotPaused\n {\n require(account != address(0), \"burn from the zero address\");\n\n shares[account] = shares[account].sub(\n sharesAmount,\n \"burn amount exceeds balance\"\n );\n _totalShare = _totalShare.sub(sharesAmount);\n }\n}\n" }, "contracts/interfaces/IAutoCompoundApe.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.10;\n\nimport \"../dependencies/openzeppelin/contracts/IERC20.sol\";\n\ninterface IAutoCompoundApe is IERC20 {\n /**\n * @dev Emitted during deposit()\n * @param user The address of the user deposit for\n * @param amountDeposited The amount being deposit\n * @param amountShare The share being deposit\n **/\n event Deposit(\n address indexed caller,\n address indexed user,\n uint256 amountDeposited,\n uint256 amountShare\n );\n\n /**\n * @dev Emitted during withdraw()\n * @param user The address of the user\n * @param amountWithdraw The amount being withdraw\n * @param amountShare The share being withdraw\n **/\n event Redeem(\n address indexed user,\n uint256 amountWithdraw,\n uint256 amountShare\n );\n\n /**\n * @dev Emitted during rescueERC20()\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amount The amount being rescued\n **/\n event RescueERC20(\n address indexed token,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @notice deposit an `amount` of ape into compound pool.\n * @param onBehalf The address of user will receive the pool share\n * @param amount The amount of ape to be deposit\n **/\n function deposit(address onBehalf, uint256 amount) external;\n\n /**\n * @notice withdraw an `amount` of ape from compound pool.\n * @param amount The amount of ape to be withdraw\n **/\n function withdraw(uint256 amount) external;\n\n /**\n * @notice collect ape reward in ApeCoinStaking and deposit to earn compound interest.\n **/\n function harvestAndCompound() external;\n}\n" }, "contracts/dependencies/yoga-labs/ApeCoinStaking.sol": { "content": "//SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\nimport \"../openzeppelin/contracts/IERC20.sol\";\nimport \"../openzeppelin/contracts/SafeERC20.sol\";\nimport \"../openzeppelin/contracts/SafeCast.sol\";\nimport \"../openzeppelin/contracts/Ownable.sol\";\nimport \"../openzeppelin/contracts/ERC721Enumerable.sol\";\n\n/**\n * @title ApeCoin Staking Contract\n * @notice Stake ApeCoin across four different pools that release hourly rewards\n * @author HorizenLabs\n */\ncontract ApeCoinStaking is Ownable {\n using SafeCast for uint256;\n using SafeCast for int256;\n\n /// @notice State for ApeCoin, BAYC, MAYC, and Pair Pools\n struct Pool {\n uint48 lastRewardedTimestampHour;\n uint16 lastRewardsRangeIndex;\n uint96 stakedAmount;\n uint96 accumulatedRewardsPerShare;\n TimeRange[] timeRanges;\n }\n\n /// @notice Pool rules valid for a given duration of time.\n /// @dev All TimeRange timestamp values must represent whole hours\n struct TimeRange {\n uint48 startTimestampHour;\n uint48 endTimestampHour;\n uint96 rewardsPerHour;\n uint96 capPerPosition;\n }\n\n /// @dev Convenience struct for front-end applications\n struct PoolUI {\n uint256 poolId;\n uint256 stakedAmount;\n TimeRange currentTimeRange;\n }\n\n /// @dev Per address amount and reward tracking\n struct Position {\n uint256 stakedAmount;\n int256 rewardsDebt;\n }\n mapping (address => Position) public addressPosition;\n\n /// @dev Struct for depositing and withdrawing from the BAYC and MAYC NFT pools\n struct SingleNft {\n uint32 tokenId;\n uint224 amount;\n }\n /// @dev Struct for depositing from the BAKC (Pair) pool\n struct PairNftDepositWithAmount {\n uint32 mainTokenId;\n uint32 bakcTokenId;\n uint184 amount;\n }\n /// @dev Struct for withdrawing from the BAKC (Pair) pool\n struct PairNftWithdrawWithAmount {\n uint32 mainTokenId;\n uint32 bakcTokenId;\n uint184 amount;\n bool isUncommit;\n }\n /// @dev Struct for claiming from an NFT pool\n struct PairNft {\n uint128 mainTokenId;\n uint128 bakcTokenId;\n }\n /// @dev NFT paired status. Can be used bi-directionally (BAYC/MAYC -> BAKC) or (BAKC -> BAYC/MAYC)\n struct PairingStatus {\n uint248 tokenId;\n bool isPaired;\n }\n\n // @dev UI focused payload\n struct DashboardStake {\n uint256 poolId;\n uint256 tokenId;\n uint256 deposited;\n uint256 unclaimed;\n uint256 rewards24hr;\n DashboardPair pair;\n }\n /// @dev Sub struct for DashboardStake\n struct DashboardPair {\n uint256 mainTokenId;\n uint256 mainTypePoolId;\n }\n /// @dev Placeholder for pair status, used by ApeCoin Pool\n DashboardPair private NULL_PAIR = DashboardPair(0, 0);\n\n /// @notice Internal ApeCoin amount for distributing staking reward claims\n IERC20 public immutable apeCoin;\n uint256 private constant APE_COIN_PRECISION = 1e18;\n uint256 private constant MIN_DEPOSIT = 1 * APE_COIN_PRECISION;\n uint256 private constant SECONDS_PER_HOUR = 3600;\n uint256 private constant SECONDS_PER_MINUTE = 60;\n\n uint256 constant APECOIN_POOL_ID = 0;\n uint256 constant BAYC_POOL_ID = 1;\n uint256 constant MAYC_POOL_ID = 2;\n uint256 constant BAKC_POOL_ID = 3;\n Pool[4] public pools;\n\n /// @dev NFT contract mapping per pool\n mapping(uint256 => ERC721Enumerable) public nftContracts;\n /// @dev poolId => tokenId => nft position\n mapping(uint256 => mapping(uint256 => Position)) public nftPosition;\n /// @dev main type pool ID: 1: BAYC 2: MAYC => main token ID => bakc token ID\n mapping(uint256 => mapping(uint256 => PairingStatus)) public mainToBakc;\n /// @dev bakc Token ID => main type pool ID: 1: BAYC 2: MAYC => main token ID\n mapping(uint256 => mapping(uint256 => PairingStatus)) public bakcToMain;\n\n /** Custom Events */\n event UpdatePool(\n uint256 indexed poolId,\n uint256 lastRewardedBlock,\n uint256 stakedAmount,\n uint256 accumulatedRewardsPerShare\n );\n event Deposit(\n address indexed user,\n uint256 amount,\n address recipient\n );\n event DepositNft(\n address indexed user,\n uint256 indexed poolId,\n uint256 amount,\n uint256 tokenId\n );\n event DepositPairNft(\n address indexed user,\n uint256 amount,\n uint256 mainTypePoolId,\n uint256 mainTokenId,\n uint256 bakcTokenId\n );\n event Withdraw(\n address indexed user,\n uint256 amount,\n address recipient\n );\n event WithdrawNft(\n address indexed user,\n uint256 indexed poolId,\n uint256 amount,\n address recipient,\n uint256 tokenId\n );\n event WithdrawPairNft(\n address indexed user,\n uint256 amount,\n uint256 mainTypePoolId,\n uint256 mainTokenId,\n uint256 bakcTokenId\n );\n event ClaimRewards(\n address indexed user,\n uint256 amount,\n address recipient\n );\n event ClaimRewardsNft(\n address indexed user,\n uint256 indexed poolId,\n uint256 amount,\n uint256 tokenId\n );\n event ClaimRewardsPairNft(\n address indexed user,\n uint256 amount,\n uint256 mainTypePoolId,\n uint256 mainTokenId,\n uint256 bakcTokenId\n );\n\n error DepositMoreThanOneAPE();\n error InvalidPoolId();\n error StartMustBeGreaterThanEnd();\n error StartNotWholeHour();\n error EndNotWholeHour();\n error StartMustEqualLastEnd();\n error CallerNotOwner();\n error MainTokenNotOwnedOrPaired();\n error BAKCNotOwnedOrPaired();\n error BAKCAlreadyPaired();\n error ExceededCapAmount();\n error NotOwnerOfMain();\n error NotOwnerOfBAKC();\n error ProvidedTokensNotPaired();\n error ExceededStakedAmount();\n error NeitherTokenInPairOwnedByCaller();\n error SplitPairCantPartiallyWithdraw();\n error UncommitWrongParameters();\n\n /**\n * @notice Construct a new ApeCoinStaking instance\n * @param _apeCoinContractAddress The ApeCoin ERC20 contract address\n * @param _baycContractAddress The BAYC NFT contract address\n * @param _maycContractAddress The MAYC NFT contract address\n * @param _bakcContractAddress The BAKC NFT contract address\n */\n constructor(\n address _apeCoinContractAddress,\n address _baycContractAddress,\n address _maycContractAddress,\n address _bakcContractAddress\n ) {\n apeCoin = IERC20(_apeCoinContractAddress);\n nftContracts[BAYC_POOL_ID] = ERC721Enumerable(_baycContractAddress);\n nftContracts[MAYC_POOL_ID] = ERC721Enumerable(_maycContractAddress);\n nftContracts[BAKC_POOL_ID] = ERC721Enumerable(_bakcContractAddress);\n }\n\n // Deposit/Commit Methods\n\n /**\n * @notice Deposit ApeCoin to the ApeCoin Pool\n * @param _amount Amount in ApeCoin\n * @param _recipient Address the deposit it stored to\n * @dev ApeCoin deposit must be >= 1 ApeCoin\n */\n function depositApeCoin(uint256 _amount, address _recipient) public {\n if (_amount < MIN_DEPOSIT) revert DepositMoreThanOneAPE();\n updatePool(APECOIN_POOL_ID);\n\n Position storage position = addressPosition[_recipient];\n _deposit(APECOIN_POOL_ID, position, _amount);\n\n apeCoin.transferFrom(msg.sender, address(this), _amount);\n\n emit Deposit(msg.sender, _amount, _recipient);\n }\n\n /**\n * @notice Deposit ApeCoin to the ApeCoin Pool\n * @param _amount Amount in ApeCoin\n * @dev Deposit on behalf of msg.sender. ApeCoin deposit must be >= 1 ApeCoin\n */\n function depositSelfApeCoin(uint256 _amount) external {\n depositApeCoin(_amount, msg.sender);\n }\n\n /**\n * @notice Deposit ApeCoin to the BAYC Pool\n * @param _nfts Array of SingleNft structs\n * @dev Commits 1 or more BAYC NFTs, each with an ApeCoin amount to the BAYC pool.\\\n * Each BAYC committed must attach an ApeCoin amount >= 1 ApeCoin and <= the BAYC pool cap amount.\n */\n function depositBAYC(SingleNft[] calldata _nfts) external {\n _depositNft(BAYC_POOL_ID, _nfts);\n }\n\n /**\n * @notice Deposit ApeCoin to the MAYC Pool\n * @param _nfts Array of SingleNft structs\n * @dev Commits 1 or more MAYC NFTs, each with an ApeCoin amount to the MAYC pool.\\\n * Each MAYC committed must attach an ApeCoin amount >= 1 ApeCoin and <= the MAYC pool cap amount.\n */\n function depositMAYC(SingleNft[] calldata _nfts) external {\n _depositNft(MAYC_POOL_ID, _nfts);\n }\n\n /**\n * @notice Deposit ApeCoin to the Pair Pool, where Pair = (BAYC + BAKC) or (MAYC + BAKC)\n * @param _baycPairs Array of PairNftDepositWithAmount structs\n * @param _maycPairs Array of PairNftDepositWithAmount structs\n * @dev Commits 1 or more Pairs, each with an ApeCoin amount to the Pair pool.\\\n * Each BAKC committed must attach an ApeCoin amount >= 1 ApeCoin and <= the Pair pool cap amount.\\\n * Example 1: BAYC + BAKC + 1 ApeCoin: [[0, 0, \"1000000000000000000\"],[]]\\\n * Example 2: MAYC + BAKC + 1 ApeCoin: [[], [0, 0, \"1000000000000000000\"]]\\\n * Example 3: (BAYC + BAKC + 1 ApeCoin) and (MAYC + BAKC + 1 ApeCoin): [[0, 0, \"1000000000000000000\"], [0, 1, \"1000000000000000000\"]]\n */\n function depositBAKC(PairNftDepositWithAmount[] calldata _baycPairs, PairNftDepositWithAmount[] calldata _maycPairs) external {\n updatePool(BAKC_POOL_ID);\n _depositPairNft(BAYC_POOL_ID, _baycPairs);\n _depositPairNft(MAYC_POOL_ID, _maycPairs);\n }\n\n // Claim Rewards Methods\n\n /**\n * @notice Claim rewards for msg.sender and send to recipient\n * @param _recipient Address to send claim reward to\n */\n function claimApeCoin(address _recipient) public {\n updatePool(APECOIN_POOL_ID);\n\n Position storage position = addressPosition[msg.sender];\n uint256 rewardsToBeClaimed = _claim(APECOIN_POOL_ID, position, _recipient);\n\n emit ClaimRewards(msg.sender, rewardsToBeClaimed, _recipient);\n }\n\n /// @notice Claim and send rewards\n function claimSelfApeCoin() external {\n claimApeCoin(msg.sender);\n }\n\n /**\n * @notice Claim rewards for array of BAYC NFTs and send to recipient\n * @param _nfts Array of NFTs owned and committed by the msg.sender\n * @param _recipient Address to send claim reward to\n */\n function claimBAYC(uint256[] calldata _nfts, address _recipient) external {\n _claimNft(BAYC_POOL_ID, _nfts, _recipient);\n }\n\n /**\n * @notice Claim rewards for array of BAYC NFTs\n * @param _nfts Array of NFTs owned and committed by the msg.sender\n */\n function claimSelfBAYC(uint256[] calldata _nfts) external {\n _claimNft(BAYC_POOL_ID, _nfts, msg.sender);\n }\n\n /**\n * @notice Claim rewards for array of MAYC NFTs and send to recipient\n * @param _nfts Array of NFTs owned and committed by the msg.sender\n * @param _recipient Address to send claim reward to\n */\n function claimMAYC(uint256[] calldata _nfts, address _recipient) external {\n _claimNft(MAYC_POOL_ID, _nfts, _recipient);\n }\n\n /**\n * @notice Claim rewards for array of MAYC NFTs\n * @param _nfts Array of NFTs owned and committed by the msg.sender\n */\n function claimSelfMAYC(uint256[] calldata _nfts) external {\n _claimNft(MAYC_POOL_ID, _nfts, msg.sender);\n }\n\n /**\n * @notice Claim rewards for array of Paired NFTs and send to recipient\n * @param _baycPairs Array of Paired BAYC NFTs owned and committed by the msg.sender\n * @param _maycPairs Array of Paired MAYC NFTs owned and committed by the msg.sender\n * @param _recipient Address to send claim reward to\n */\n function claimBAKC(PairNft[] calldata _baycPairs, PairNft[] calldata _maycPairs, address _recipient) public {\n updatePool(BAKC_POOL_ID);\n _claimPairNft(BAYC_POOL_ID, _baycPairs, _recipient);\n _claimPairNft(MAYC_POOL_ID, _maycPairs, _recipient);\n }\n\n /**\n * @notice Claim rewards for array of Paired NFTs\n * @param _baycPairs Array of Paired BAYC NFTs owned and committed by the msg.sender\n * @param _maycPairs Array of Paired MAYC NFTs owned and committed by the msg.sender\n */\n function claimSelfBAKC(PairNft[] calldata _baycPairs, PairNft[] calldata _maycPairs) external {\n claimBAKC(_baycPairs, _maycPairs, msg.sender);\n }\n\n // Uncommit/Withdraw Methods\n\n /**\n * @notice Withdraw staked ApeCoin from the ApeCoin pool. Performs an automatic claim as part of the withdraw process.\n * @param _amount Amount of ApeCoin\n * @param _recipient Address to send withdraw amount and claim to\n */\n function withdrawApeCoin(uint256 _amount, address _recipient) public {\n updatePool(APECOIN_POOL_ID);\n\n Position storage position = addressPosition[msg.sender];\n if (_amount == position.stakedAmount) {\n uint256 rewardsToBeClaimed = _claim(APECOIN_POOL_ID, position, _recipient);\n emit ClaimRewards(msg.sender, rewardsToBeClaimed, _recipient);\n }\n _withdraw(APECOIN_POOL_ID, position, _amount);\n\n apeCoin.transfer(_recipient, _amount);\n\n emit Withdraw(msg.sender, _amount, _recipient);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the ApeCoin pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _amount Amount of ApeCoin\n */\n function withdrawSelfApeCoin(uint256 _amount) external {\n withdrawApeCoin(_amount, msg.sender);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the BAYC pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _nfts Array of BAYC NFT's with staked amounts\n * @param _recipient Address to send withdraw amount and claim to\n */\n function withdrawBAYC(SingleNft[] calldata _nfts, address _recipient) external {\n _withdrawNft(BAYC_POOL_ID, _nfts, _recipient);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the BAYC pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _nfts Array of BAYC NFT's with staked amounts\n */\n function withdrawSelfBAYC(SingleNft[] calldata _nfts) external {\n _withdrawNft(BAYC_POOL_ID, _nfts, msg.sender);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the MAYC pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _nfts Array of MAYC NFT's with staked amounts\n * @param _recipient Address to send withdraw amount and claim to\n */\n function withdrawMAYC(SingleNft[] calldata _nfts, address _recipient) external {\n _withdrawNft(MAYC_POOL_ID, _nfts, _recipient);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the MAYC pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _nfts Array of MAYC NFT's with staked amounts\n */\n function withdrawSelfMAYC(SingleNft[] calldata _nfts) external {\n _withdrawNft(MAYC_POOL_ID, _nfts, msg.sender);\n }\n\n /**\n * @notice Withdraw staked ApeCoin from the Pair pool. If withdraw is total staked amount, performs an automatic claim.\n * @param _baycPairs Array of Paired BAYC NFT's with staked amounts and isUncommit boolean\n * @param _maycPairs Array of Paired MAYC NFT's with staked amounts and isUncommit boolean\n * @dev if pairs have split ownership and BAKC is attempting a withdraw, the withdraw must be for the total staked amount\n */\n function withdrawBAKC(PairNftWithdrawWithAmount[] calldata _baycPairs, PairNftWithdrawWithAmount[] calldata _maycPairs) external {\n updatePool(BAKC_POOL_ID);\n _withdrawPairNft(BAYC_POOL_ID, _baycPairs);\n _withdrawPairNft(MAYC_POOL_ID, _maycPairs);\n }\n\n // Time Range Methods\n\n /**\n * @notice Add single time range with a given rewards per hour for a given pool\n * @dev In practice one Time Range will represent one quarter (defined by `_startTimestamp`and `_endTimeStamp` as whole hours)\n * where the rewards per hour is constant for a given pool.\n * @param _poolId Available pool values 0-3\n * @param _amount Total amount of ApeCoin to be distributed over the range\n * @param _startTimestamp Whole hour timestamp representation\n * @param _endTimeStamp Whole hour timestamp representation\n * @param _capPerPosition Per position cap amount determined by poolId\n */\n function addTimeRange(\n uint256 _poolId,\n uint256 _amount,\n uint256 _startTimestamp,\n uint256 _endTimeStamp,\n uint256 _capPerPosition) external onlyOwner\n {\n if (_poolId > BAKC_POOL_ID) revert InvalidPoolId();\n if (_startTimestamp >= _endTimeStamp) revert StartMustBeGreaterThanEnd();\n if (getMinute(_startTimestamp) > 0 || getSecond(_startTimestamp) > 0) revert StartNotWholeHour();\n if (getMinute(_endTimeStamp) > 0 || getSecond(_endTimeStamp) > 0) revert EndNotWholeHour();\n\n Pool storage pool = pools[_poolId];\n uint256 length = pool.timeRanges.length;\n if (length > 0) {\n if (_startTimestamp != pool.timeRanges[length - 1].endTimestampHour) revert StartMustEqualLastEnd();\n }\n\n uint256 hoursInSeconds = _endTimeStamp - _startTimestamp;\n uint256 rewardsPerHour = _amount * SECONDS_PER_HOUR / hoursInSeconds;\n\n TimeRange memory next = TimeRange(_startTimestamp.toUint48(), _endTimeStamp.toUint48(),\n rewardsPerHour.toUint96(), _capPerPosition.toUint96());\n pool.timeRanges.push(next);\n }\n\n /**\n * @notice Removes the last Time Range for a given pool.\n * @param _poolId Available pool values 0-3\n */\n function removeLastTimeRange(uint256 _poolId) external onlyOwner {\n pools[_poolId].timeRanges.pop();\n }\n\n /**\n * @notice Lookup method for a TimeRange struct\n * @return TimeRange A Pool's timeRanges struct by index.\n * @param _poolId Available pool values 0-3\n * @param _index Target index in a Pool's timeRanges array\n */\n function getTimeRangeBy(uint256 _poolId, uint256 _index) public view returns (TimeRange memory) {\n return pools[_poolId].timeRanges[_index];\n }\n\n // Pool Methods\n\n /**\n * @notice Lookup available rewards for a pool over a given time range\n * @return uint256 The amount of ApeCoin rewards to be distributed by pool for a given time range\n * @return uint256 The amount of time ranges\n * @param _poolId Available pool values 0-3\n * @param _from Whole hour timestamp representation\n * @param _to Whole hour timestamp representation\n */\n function rewardsBy(uint256 _poolId, uint256 _from, uint256 _to) public view returns (uint256, uint256) {\n Pool memory pool = pools[_poolId];\n\n uint256 currentIndex = pool.lastRewardsRangeIndex;\n if(_to < pool.timeRanges[0].startTimestampHour) return (0, currentIndex);\n\n while(_from > pool.timeRanges[currentIndex].endTimestampHour && _to > pool.timeRanges[currentIndex].endTimestampHour) {\n unchecked {\n ++currentIndex;\n }\n }\n\n uint256 rewards;\n TimeRange memory current;\n uint256 startTimestampHour;\n uint256 endTimestampHour;\n uint256 length = pool.timeRanges.length;\n for(uint256 i = currentIndex; i < length;) {\n current = pool.timeRanges[i];\n startTimestampHour = _from <= current.startTimestampHour ? current.startTimestampHour : _from;\n endTimestampHour = _to <= current.endTimestampHour ? _to : current.endTimestampHour;\n\n rewards = rewards + (endTimestampHour - startTimestampHour) * current.rewardsPerHour / SECONDS_PER_HOUR;\n\n if(_to <= endTimestampHour) {\n return (rewards, i);\n }\n unchecked {\n ++i;\n }\n }\n\n return (rewards, length - 1);\n }\n\n /**\n * @notice Updates reward variables `lastRewardedTimestampHour`, `accumulatedRewardsPerShare` and `lastRewardsRangeIndex`\n * for a given pool.\n * @param _poolId Available pool values 0-3\n */\n function updatePool(uint256 _poolId) public {\n Pool storage pool = pools[_poolId];\n\n if (block.timestamp < pool.timeRanges[0].startTimestampHour) return;\n if (block.timestamp <= pool.lastRewardedTimestampHour + SECONDS_PER_HOUR) return;\n\n uint48 lastTimestampHour = pool.timeRanges[pool.timeRanges.length-1].endTimestampHour;\n uint48 previousTimestampHour = getPreviousTimestampHour().toUint48();\n\n if (pool.stakedAmount == 0) {\n pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour;\n return;\n }\n\n (uint256 rewards, uint256 index) = rewardsBy(_poolId, pool.lastRewardedTimestampHour, previousTimestampHour);\n if (pool.lastRewardsRangeIndex != index) {\n pool.lastRewardsRangeIndex = index.toUint16();\n }\n pool.accumulatedRewardsPerShare = (pool.accumulatedRewardsPerShare + (rewards * APE_COIN_PRECISION) / pool.stakedAmount).toUint96();\n pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour;\n\n emit UpdatePool(_poolId, pool.lastRewardedTimestampHour, pool.stakedAmount, pool.accumulatedRewardsPerShare);\n }\n\n // Read Methods\n\n function getCurrentTimeRangeIndex(Pool memory pool) private view returns (uint256) {\n uint256 current = pool.lastRewardsRangeIndex;\n\n if (block.timestamp < pool.timeRanges[current].startTimestampHour) return current;\n for(current = pool.lastRewardsRangeIndex; current < pool.timeRanges.length; ++current) {\n TimeRange memory currentTimeRange = pool.timeRanges[current];\n if (currentTimeRange.startTimestampHour <= block.timestamp && block.timestamp <= currentTimeRange.endTimestampHour) return current;\n }\n revert(\"distribution ended\");\n }\n\n /**\n * @notice Fetches a PoolUI struct (poolId, stakedAmount, currentTimeRange) for each reward pool\n * @return PoolUI for ApeCoin.\n * @return PoolUI for BAYC.\n * @return PoolUI for MAYC.\n * @return PoolUI for BAKC.\n */\n function getPoolsUI() public view returns (PoolUI memory, PoolUI memory, PoolUI memory, PoolUI memory) {\n Pool memory apeCoinPool = pools[0];\n Pool memory baycPool = pools[1];\n Pool memory maycPool = pools[2];\n Pool memory bakcPool = pools[3];\n uint256 current = getCurrentTimeRangeIndex(apeCoinPool);\n return (PoolUI(0,apeCoinPool.stakedAmount, apeCoinPool.timeRanges[current]),\n PoolUI(1,baycPool.stakedAmount, baycPool.timeRanges[current]),\n PoolUI(2,maycPool.stakedAmount, maycPool.timeRanges[current]),\n PoolUI(3,bakcPool.stakedAmount, bakcPool.timeRanges[current]));\n }\n\n /**\n * @notice Fetches an address total staked amount, used by voting contract\n * @return amount uint256 staked amount for all pools.\n * @param _address An Ethereum address\n */\n function stakedTotal(address _address) external view returns (uint256) {\n uint256 total = addressPosition[_address].stakedAmount;\n\n total += _stakedTotal(BAYC_POOL_ID, _address);\n total += _stakedTotal(MAYC_POOL_ID, _address);\n total += _stakedTotalPair(_address);\n\n return total;\n }\n\n function _stakedTotal(uint256 _poolId, address _addr) private view returns (uint256) {\n uint256 total = 0;\n uint256 nftCount = nftContracts[_poolId].balanceOf(_addr);\n for(uint256 i = 0; i < nftCount; ++i) {\n uint256 tokenId = nftContracts[_poolId].tokenOfOwnerByIndex(_addr, i);\n total += nftPosition[_poolId][tokenId].stakedAmount;\n }\n\n return total;\n }\n\n function _stakedTotalPair(address _addr) private view returns (uint256) {\n uint256 total = 0;\n\n uint256 nftCount = nftContracts[BAYC_POOL_ID].balanceOf(_addr);\n for(uint256 i = 0; i < nftCount; ++i) {\n uint256 baycTokenId = nftContracts[BAYC_POOL_ID].tokenOfOwnerByIndex(_addr, i);\n if (mainToBakc[BAYC_POOL_ID][baycTokenId].isPaired) {\n uint256 bakcTokenId = mainToBakc[BAYC_POOL_ID][baycTokenId].tokenId;\n total += nftPosition[BAKC_POOL_ID][bakcTokenId].stakedAmount;\n }\n }\n\n nftCount = nftContracts[MAYC_POOL_ID].balanceOf(_addr);\n for(uint256 i = 0; i < nftCount; ++i) {\n uint256 maycTokenId = nftContracts[MAYC_POOL_ID].tokenOfOwnerByIndex(_addr, i);\n if (mainToBakc[MAYC_POOL_ID][maycTokenId].isPaired) {\n uint256 bakcTokenId = mainToBakc[MAYC_POOL_ID][maycTokenId].tokenId;\n total += nftPosition[BAKC_POOL_ID][bakcTokenId].stakedAmount;\n }\n }\n\n return total;\n }\n\n /**\n * @notice Fetches a DashboardStake = [poolId, tokenId, deposited, unclaimed, rewards24Hrs, paired] \\\n * for each pool, for an Ethereum address\n * @return dashboardStakes An array of DashboardStake structs\n * @param _address An Ethereum address\n */\n function getAllStakes(address _address) public view returns (DashboardStake[] memory) {\n\n DashboardStake memory apeCoinStake = getApeCoinStake(_address);\n DashboardStake[] memory baycStakes = getBaycStakes(_address);\n DashboardStake[] memory maycStakes = getMaycStakes(_address);\n DashboardStake[] memory bakcStakes = getBakcStakes(_address);\n DashboardStake[] memory splitStakes = getSplitStakes(_address);\n\n uint256 count = (baycStakes.length + maycStakes.length + bakcStakes.length + splitStakes.length + 1);\n DashboardStake[] memory allStakes = new DashboardStake[](count);\n\n uint256 offset = 0;\n allStakes[offset] = apeCoinStake;\n ++offset;\n\n for(uint256 i = 0; i < baycStakes.length; ++i) {\n allStakes[offset] = baycStakes[i];\n ++offset;\n }\n\n for(uint256 i = 0; i < maycStakes.length; ++i) {\n allStakes[offset] = maycStakes[i];\n ++offset;\n }\n\n for(uint256 i = 0; i < bakcStakes.length; ++i) {\n allStakes[offset] = bakcStakes[i];\n ++offset;\n }\n\n for(uint256 i = 0; i < splitStakes.length; ++i) {\n allStakes[offset] = splitStakes[i];\n ++offset;\n }\n\n return allStakes;\n }\n\n /**\n * @notice Fetches a DashboardStake for the ApeCoin pool\n * @return dashboardStake A dashboardStake struct\n * @param _address An Ethereum address\n */\n function getApeCoinStake(address _address) public view returns (DashboardStake memory) {\n uint256 tokenId = 0;\n uint256 deposited = addressPosition[_address].stakedAmount;\n uint256 unclaimed = deposited > 0 ? this.pendingRewards(0, _address, tokenId) : 0;\n uint256 rewards24Hrs = deposited > 0 ? _estimate24HourRewards(0, _address, 0) : 0;\n\n return DashboardStake(APECOIN_POOL_ID, tokenId, deposited, unclaimed, rewards24Hrs, NULL_PAIR);\n }\n\n /**\n * @notice Fetches an array of DashboardStakes for the BAYC pool\n * @return dashboardStakes An array of DashboardStake structs\n */\n function getBaycStakes(address _address) public view returns (DashboardStake[] memory) {\n return _getStakes(_address, BAYC_POOL_ID);\n }\n\n /**\n * @notice Fetches an array of DashboardStakes for the MAYC pool\n * @return dashboardStakes An array of DashboardStake structs\n */\n function getMaycStakes(address _address) public view returns (DashboardStake[] memory) {\n return _getStakes(_address, MAYC_POOL_ID);\n }\n\n /**\n * @notice Fetches an array of DashboardStakes for the BAKC pool\n * @return dashboardStakes An array of DashboardStake structs\n */\n function getBakcStakes(address _address) public view returns (DashboardStake[] memory) {\n return _getStakes(_address, BAKC_POOL_ID);\n }\n\n /**\n * @notice Fetches an array of DashboardStakes for the Pair Pool when ownership is split \\\n * ie (BAYC/MAYC) and BAKC in pair pool have different owners.\n * @return dashboardStakes An array of DashboardStake structs\n * @param _address An Ethereum address\n */\n function getSplitStakes(address _address) public view returns (DashboardStake[] memory) {\n uint256 baycSplits = _getSplitStakeCount(nftContracts[BAYC_POOL_ID].balanceOf(_address), _address, BAYC_POOL_ID);\n uint256 maycSplits = _getSplitStakeCount(nftContracts[MAYC_POOL_ID].balanceOf(_address), _address, MAYC_POOL_ID);\n uint256 totalSplits = baycSplits + maycSplits;\n\n if(totalSplits == 0) {\n return new DashboardStake[](0);\n }\n\n DashboardStake[] memory baycSplitStakes = _getSplitStakes(baycSplits, _address, BAYC_POOL_ID);\n DashboardStake[] memory maycSplitStakes = _getSplitStakes(maycSplits, _address, MAYC_POOL_ID);\n\n DashboardStake[] memory splitStakes = new DashboardStake[](totalSplits);\n uint256 offset = 0;\n for(uint256 i = 0; i < baycSplitStakes.length; ++i) {\n splitStakes[offset] = baycSplitStakes[i];\n ++offset;\n }\n\n for(uint256 i = 0; i < maycSplitStakes.length; ++i) {\n splitStakes[offset] = maycSplitStakes[i];\n ++offset;\n }\n\n return splitStakes;\n }\n\n function _getSplitStakes(uint256 splits, address _address, uint256 _mainPoolId) private view returns (DashboardStake[] memory) {\n\n DashboardStake[] memory dashboardStakes = new DashboardStake[](splits);\n uint256 counter;\n\n for(uint256 i = 0; i < nftContracts[_mainPoolId].balanceOf(_address); ++i) {\n uint256 mainTokenId = nftContracts[_mainPoolId].tokenOfOwnerByIndex(_address, i);\n if(mainToBakc[_mainPoolId][mainTokenId].isPaired) {\n uint256 bakcTokenId = mainToBakc[_mainPoolId][mainTokenId].tokenId;\n address currentOwner = nftContracts[BAKC_POOL_ID].ownerOf(bakcTokenId);\n\n /* Split Pair Check*/\n if (currentOwner != _address) {\n uint256 deposited = nftPosition[BAKC_POOL_ID][bakcTokenId].stakedAmount;\n uint256 unclaimed = deposited > 0 ? this.pendingRewards(BAKC_POOL_ID, currentOwner, bakcTokenId) : 0;\n uint256 rewards24Hrs = deposited > 0 ? _estimate24HourRewards(BAKC_POOL_ID, currentOwner, bakcTokenId): 0;\n\n DashboardPair memory pair = NULL_PAIR;\n if(bakcToMain[bakcTokenId][_mainPoolId].isPaired) {\n pair = DashboardPair(bakcToMain[bakcTokenId][_mainPoolId].tokenId, _mainPoolId);\n }\n\n DashboardStake memory dashboardStake = DashboardStake(BAKC_POOL_ID, bakcTokenId, deposited, unclaimed, rewards24Hrs, pair);\n dashboardStakes[counter] = dashboardStake;\n ++counter;\n }\n }\n }\n\n return dashboardStakes;\n }\n\n function _getSplitStakeCount(uint256 nftCount, address _address, uint256 _mainPoolId) private view returns (uint256) {\n uint256 splitCount;\n for(uint256 i = 0; i < nftCount; ++i) {\n uint256 mainTokenId = nftContracts[_mainPoolId].tokenOfOwnerByIndex(_address, i);\n if(mainToBakc[_mainPoolId][mainTokenId].isPaired) {\n uint256 bakcTokenId = mainToBakc[_mainPoolId][mainTokenId].tokenId;\n address currentOwner = nftContracts[BAKC_POOL_ID].ownerOf(bakcTokenId);\n if (currentOwner != _address) {\n ++splitCount;\n }\n }\n }\n\n return splitCount;\n }\n\n function _getStakes(address _address, uint256 _poolId) private view returns (DashboardStake[] memory) {\n uint256 nftCount = nftContracts[_poolId].balanceOf(_address);\n DashboardStake[] memory dashboardStakes = nftCount > 0 ? new DashboardStake[](nftCount) : new DashboardStake[](0);\n\n if(nftCount == 0) {\n return dashboardStakes;\n }\n\n for(uint256 i = 0; i < nftCount; ++i) {\n uint256 tokenId = nftContracts[_poolId].tokenOfOwnerByIndex(_address, i);\n uint256 deposited = nftPosition[_poolId][tokenId].stakedAmount;\n uint256 unclaimed = deposited > 0 ? this.pendingRewards(_poolId, _address, tokenId) : 0;\n uint256 rewards24Hrs = deposited > 0 ? _estimate24HourRewards(_poolId, _address, tokenId): 0;\n\n DashboardPair memory pair = NULL_PAIR;\n if(_poolId == BAKC_POOL_ID) {\n if(bakcToMain[tokenId][BAYC_POOL_ID].isPaired) {\n pair = DashboardPair(bakcToMain[tokenId][BAYC_POOL_ID].tokenId, BAYC_POOL_ID);\n } else if(bakcToMain[tokenId][MAYC_POOL_ID].isPaired) {\n pair = DashboardPair(bakcToMain[tokenId][MAYC_POOL_ID].tokenId, MAYC_POOL_ID);\n }\n }\n\n DashboardStake memory dashboardStake = DashboardStake(_poolId, tokenId, deposited, unclaimed, rewards24Hrs, pair);\n dashboardStakes[i] = dashboardStake;\n }\n\n return dashboardStakes;\n }\n\n function _estimate24HourRewards(uint256 _poolId, address _address, uint256 _tokenId) private view returns (uint256) {\n Pool memory pool = pools[_poolId];\n Position memory position = _poolId == 0 ? addressPosition[_address]: nftPosition[_poolId][_tokenId];\n\n TimeRange memory rewards = getTimeRangeBy(_poolId, pool.lastRewardsRangeIndex);\n return (position.stakedAmount * uint256(rewards.rewardsPerHour) * 24) / uint256(pool.stakedAmount);\n }\n\n /**\n * @notice Fetches the current amount of claimable ApeCoin rewards for a given position from a given pool.\n * @return uint256 value of pending rewards\n * @param _poolId Available pool values 0-3\n * @param _address Address to lookup Position for\n * @param _tokenId An NFT id\n */\n function pendingRewards(uint256 _poolId, address _address, uint256 _tokenId) external view returns (uint256) {\n Pool memory pool = pools[_poolId];\n Position memory position = _poolId == 0 ? addressPosition[_address]: nftPosition[_poolId][_tokenId];\n\n (uint256 rewardsSinceLastCalculated,) = rewardsBy(_poolId, pool.lastRewardedTimestampHour, getPreviousTimestampHour());\n uint256 accumulatedRewardsPerShare = pool.accumulatedRewardsPerShare;\n\n if (block.timestamp > pool.lastRewardedTimestampHour + SECONDS_PER_HOUR && pool.stakedAmount != 0) {\n accumulatedRewardsPerShare = accumulatedRewardsPerShare + rewardsSinceLastCalculated * APE_COIN_PRECISION / pool.stakedAmount;\n }\n return ((position.stakedAmount * accumulatedRewardsPerShare).toInt256() - position.rewardsDebt).toUint256() / APE_COIN_PRECISION;\n }\n\n // Convenience methods for timestamp calculation\n\n /// @notice the minutes (0 to 59) of a timestamp\n function getMinute(uint256 timestamp) internal pure returns (uint256 minute) {\n uint256 secs = timestamp % SECONDS_PER_HOUR;\n minute = secs / SECONDS_PER_MINUTE;\n }\n\n /// @notice the seconds (0 to 59) of a timestamp\n function getSecond(uint256 timestamp) internal pure returns (uint256 second) {\n second = timestamp % SECONDS_PER_MINUTE;\n }\n\n /// @notice the previous whole hour of a timestamp\n function getPreviousTimestampHour() internal view returns (uint256) {\n return block.timestamp - (getMinute(block.timestamp) * 60 + getSecond(block.timestamp));\n }\n\n // Private Methods - shared logic\n function _deposit(uint256 _poolId, Position storage _position, uint256 _amount) private {\n Pool storage pool = pools[_poolId];\n\n _position.stakedAmount += _amount;\n pool.stakedAmount += _amount.toUint96();\n _position.rewardsDebt += (_amount * pool.accumulatedRewardsPerShare).toInt256();\n }\n\n function _depositNft(uint256 _poolId, SingleNft[] calldata _nfts) private {\n updatePool(_poolId);\n uint256 tokenId;\n uint256 amount;\n Position storage position;\n uint256 length = _nfts.length;\n uint256 totalDeposit;\n for(uint256 i; i < length;) {\n tokenId = _nfts[i].tokenId;\n position = nftPosition[_poolId][tokenId];\n if (position.stakedAmount == 0) {\n if (nftContracts[_poolId].ownerOf(tokenId) != msg.sender) revert CallerNotOwner();\n }\n amount = _nfts[i].amount;\n _depositNftGuard(_poolId, position, amount);\n totalDeposit += amount;\n emit DepositNft(msg.sender, _poolId, amount, tokenId);\n unchecked {\n ++i;\n }\n }\n if (totalDeposit > 0) apeCoin.transferFrom(msg.sender, address(this), totalDeposit);\n }\n\n function _depositPairNft(uint256 mainTypePoolId, PairNftDepositWithAmount[] calldata _nfts) private {\n uint256 length = _nfts.length;\n uint256 totalDeposit;\n PairNftDepositWithAmount memory pair;\n Position storage position;\n for(uint256 i; i < length;) {\n pair = _nfts[i];\n position = nftPosition[BAKC_POOL_ID][pair.bakcTokenId];\n\n if(position.stakedAmount == 0) {\n if (nftContracts[mainTypePoolId].ownerOf(pair.mainTokenId) != msg.sender\n || mainToBakc[mainTypePoolId][pair.mainTokenId].isPaired) revert MainTokenNotOwnedOrPaired();\n if (nftContracts[BAKC_POOL_ID].ownerOf(pair.bakcTokenId) != msg.sender\n || bakcToMain[pair.bakcTokenId][mainTypePoolId].isPaired) revert BAKCNotOwnedOrPaired();\n\n mainToBakc[mainTypePoolId][pair.mainTokenId] = PairingStatus(pair.bakcTokenId, true);\n bakcToMain[pair.bakcTokenId][mainTypePoolId] = PairingStatus(pair.mainTokenId, true);\n } else if (pair.mainTokenId != bakcToMain[pair.bakcTokenId][mainTypePoolId].tokenId\n || pair.bakcTokenId != mainToBakc[mainTypePoolId][pair.mainTokenId].tokenId)\n revert BAKCAlreadyPaired();\n\n _depositNftGuard(BAKC_POOL_ID, position, pair.amount);\n totalDeposit += pair.amount;\n emit DepositPairNft(msg.sender, pair.amount, mainTypePoolId, pair.mainTokenId, pair.bakcTokenId);\n unchecked {\n ++i;\n }\n }\n if (totalDeposit > 0) apeCoin.transferFrom(msg.sender, address(this), totalDeposit);\n }\n\n function _depositNftGuard(uint256 _poolId, Position storage _position, uint256 _amount) private {\n if (_amount < MIN_DEPOSIT) revert DepositMoreThanOneAPE();\n if (_amount + _position.stakedAmount > pools[_poolId].timeRanges[pools[_poolId].lastRewardsRangeIndex].capPerPosition)\n revert ExceededCapAmount();\n\n _deposit(_poolId, _position, _amount);\n }\n\n function _claim(uint256 _poolId, Position storage _position, address _recipient) private returns (uint256 rewardsToBeClaimed) {\n Pool storage pool = pools[_poolId];\n\n int256 accumulatedApeCoins = (_position.stakedAmount * uint256(pool.accumulatedRewardsPerShare)).toInt256();\n rewardsToBeClaimed = (accumulatedApeCoins - _position.rewardsDebt).toUint256() / APE_COIN_PRECISION;\n\n _position.rewardsDebt = accumulatedApeCoins;\n\n if (rewardsToBeClaimed != 0) {\n apeCoin.transfer(_recipient, rewardsToBeClaimed);\n }\n }\n\n function _claimNft(uint256 _poolId, uint256[] calldata _nfts, address _recipient) private {\n updatePool(_poolId);\n uint256 tokenId;\n uint256 rewardsToBeClaimed;\n uint256 length = _nfts.length;\n for(uint256 i; i < length;) {\n tokenId = _nfts[i];\n if (nftContracts[_poolId].ownerOf(tokenId) != msg.sender) revert CallerNotOwner();\n Position storage position = nftPosition[_poolId][tokenId];\n rewardsToBeClaimed = _claim(_poolId, position, _recipient);\n emit ClaimRewardsNft(msg.sender, _poolId, rewardsToBeClaimed, tokenId);\n unchecked {\n ++i;\n }\n }\n }\n\n function _claimPairNft(uint256 mainTypePoolId, PairNft[] calldata _pairs, address _recipient) private {\n uint256 length = _pairs.length;\n uint256 mainTokenId;\n uint256 bakcTokenId;\n Position storage position;\n PairingStatus storage mainToSecond;\n PairingStatus storage secondToMain;\n for(uint256 i; i < length;) {\n mainTokenId = _pairs[i].mainTokenId;\n if (nftContracts[mainTypePoolId].ownerOf(mainTokenId) != msg.sender) revert NotOwnerOfMain();\n\n bakcTokenId = _pairs[i].bakcTokenId;\n if (nftContracts[BAKC_POOL_ID].ownerOf(bakcTokenId) != msg.sender) revert NotOwnerOfBAKC();\n\n mainToSecond = mainToBakc[mainTypePoolId][mainTokenId];\n secondToMain = bakcToMain[bakcTokenId][mainTypePoolId];\n\n if (mainToSecond.tokenId != bakcTokenId || !mainToSecond.isPaired\n || secondToMain.tokenId != mainTokenId || !secondToMain.isPaired) revert ProvidedTokensNotPaired();\n\n position = nftPosition[BAKC_POOL_ID][bakcTokenId];\n uint256 rewardsToBeClaimed = _claim(BAKC_POOL_ID, position, _recipient);\n emit ClaimRewardsPairNft(msg.sender, rewardsToBeClaimed, mainTypePoolId, mainTokenId, bakcTokenId);\n unchecked {\n ++i;\n }\n }\n }\n\n function _withdraw(uint256 _poolId, Position storage _position, uint256 _amount) private {\n if (_amount > _position.stakedAmount) revert ExceededStakedAmount();\n\n Pool storage pool = pools[_poolId];\n\n _position.stakedAmount -= _amount;\n pool.stakedAmount -= _amount.toUint96();\n _position.rewardsDebt -= (_amount * pool.accumulatedRewardsPerShare).toInt256();\n }\n\n function _withdrawNft(uint256 _poolId, SingleNft[] calldata _nfts, address _recipient) private {\n updatePool(_poolId);\n uint256 tokenId;\n uint256 amount;\n uint256 length = _nfts.length;\n uint256 totalWithdraw;\n Position storage position;\n for(uint256 i; i < length;) {\n tokenId = _nfts[i].tokenId;\n if (nftContracts[_poolId].ownerOf(tokenId) != msg.sender) revert CallerNotOwner();\n\n amount = _nfts[i].amount;\n position = nftPosition[_poolId][tokenId];\n if (amount == position.stakedAmount) {\n uint256 rewardsToBeClaimed = _claim(_poolId, position, _recipient);\n emit ClaimRewardsNft(msg.sender, _poolId, rewardsToBeClaimed, tokenId);\n }\n _withdraw(_poolId, position, amount);\n totalWithdraw += amount;\n emit WithdrawNft(msg.sender, _poolId, amount, _recipient, tokenId);\n unchecked {\n ++i;\n }\n }\n if (totalWithdraw > 0) apeCoin.transfer(_recipient, totalWithdraw);\n }\n\n function _withdrawPairNft(uint256 mainTypePoolId, PairNftWithdrawWithAmount[] calldata _nfts) private {\n address mainTokenOwner;\n address bakcOwner;\n PairNftWithdrawWithAmount memory pair;\n PairingStatus storage mainToSecond;\n PairingStatus storage secondToMain;\n Position storage position;\n uint256 length = _nfts.length;\n for(uint256 i; i < length;) {\n pair = _nfts[i];\n mainTokenOwner = nftContracts[mainTypePoolId].ownerOf(pair.mainTokenId);\n bakcOwner = nftContracts[BAKC_POOL_ID].ownerOf(pair.bakcTokenId);\n\n if (mainTokenOwner != msg.sender) {\n if (bakcOwner != msg.sender) revert NeitherTokenInPairOwnedByCaller();\n }\n\n mainToSecond = mainToBakc[mainTypePoolId][pair.mainTokenId];\n secondToMain = bakcToMain[pair.bakcTokenId][mainTypePoolId];\n\n if (mainToSecond.tokenId != pair.bakcTokenId || !mainToSecond.isPaired\n || secondToMain.tokenId != pair.mainTokenId || !secondToMain.isPaired) revert ProvidedTokensNotPaired();\n\n position = nftPosition[BAKC_POOL_ID][pair.bakcTokenId];\n if(!pair.isUncommit) {\n if(pair.amount == position.stakedAmount) revert UncommitWrongParameters();\n }\n if (mainTokenOwner != bakcOwner) {\n if (!pair.isUncommit) revert SplitPairCantPartiallyWithdraw();\n }\n\n if (pair.isUncommit) {\n uint256 rewardsToBeClaimed = _claim(BAKC_POOL_ID, position, bakcOwner);\n mainToBakc[mainTypePoolId][pair.mainTokenId] = PairingStatus(0, false);\n bakcToMain[pair.bakcTokenId][mainTypePoolId] = PairingStatus(0, false);\n emit ClaimRewardsPairNft(msg.sender, rewardsToBeClaimed, mainTypePoolId, pair.mainTokenId, pair.bakcTokenId);\n }\n uint256 finalAmountToWithdraw = pair.isUncommit ? position.stakedAmount: pair.amount;\n _withdraw(BAKC_POOL_ID, position, finalAmountToWithdraw);\n apeCoin.transfer(mainTokenOwner, finalAmountToWithdraw);\n emit WithdrawPairNft(msg.sender, finalAmountToWithdraw, mainTypePoolId, pair.mainTokenId, pair.bakcTokenId);\n unchecked {\n ++i;\n }\n }\n }\n\n}\n" }, "contracts/dependencies/openzeppelin/upgradeability/OwnableUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./ContextUpgradeable.sol\";\nimport \"./Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal onlyInitializing {\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal onlyInitializing {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}" }, "contracts/dependencies/openzeppelin/upgradeability/Initializable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../contracts/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) ||\n (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n require(\n !_initializing && _initialized < version,\n \"Initializable: contract is already initialized\"\n );\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized < type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount)\n external\n returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender)\n external\n view\n returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(\n address indexed owner,\n address indexed spender,\n uint256 value\n );\n}\n" }, "contracts/dependencies/openzeppelin/contracts/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity 0.8.10;\n\nimport \"./IERC20.sol\";\nimport \"./draft-IERC20Permit.sol\";\nimport \"./Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}" }, "contracts/interfaces/ICApe.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.10;\n\nimport \"../dependencies/openzeppelin/contracts/IERC20.sol\";\n\ninterface ICApe is IERC20 {\n /**\n * @return the amount of shares that corresponds to `amount` protocol-controlled Ape.\n */\n function getShareByPooledApe(uint256 amount)\n external\n view\n returns (uint256);\n\n /**\n * @return the amount of Ape that corresponds to `sharesAmount` token shares.\n */\n function getPooledApeByShares(uint256 sharesAmount)\n external\n view\n returns (uint256);\n}\n" }, "contracts/dependencies/openzeppelin/upgradeability/ContextUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"./Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}" }, "contracts/dependencies/openzeppelin/contracts/Context.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return payable(msg.sender);\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n" }, "contracts/dependencies/openzeppelin/upgradeability/PausableUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./ContextUpgradeable.sol\";\nimport \"./Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n function __Pausable_init() internal onlyInitializing {\n __Pausable_init_unchained();\n }\n\n function __Pausable_init_unchained() internal onlyInitializing {\n _paused = false;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is not paused.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n modifier whenNotPaused() {\n _requireNotPaused();\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n modifier whenPaused() {\n _requirePaused();\n _;\n }\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view virtual returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Throws if the contract is paused.\n */\n function _requireNotPaused() internal view virtual {\n require(!paused(), \"Pausable: paused\");\n }\n\n /**\n * @dev Throws if the contract is not paused.\n */\n function _requirePaused() internal view virtual {\n require(paused(), \"Pausable: not paused\");\n }\n\n /**\n * @dev Triggers stopped state.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}" }, "contracts/dependencies/openzeppelin/contracts/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.10;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/SafeMath.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.10;\n\n/// @title Optimized overflow and underflow safe math operations\n/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost\nlibrary SafeMath {\n /// @notice Returns x + y, reverts if sum overflows uint256\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n unchecked {\n require((z = x + y) >= x);\n }\n }\n\n /// @notice Returns x - y, reverts if underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n unchecked {\n require((z = x - y) <= x);\n }\n }\n\n /// @notice Returns x - y, reverts if underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @param message The error msg\n /// @return z The difference of x and y\n function sub(\n uint256 x,\n uint256 y,\n string memory message\n ) internal pure returns (uint256 z) {\n unchecked {\n require((z = x - y) <= x, message);\n }\n }\n\n /// @notice Returns x * y, reverts if overflows\n /// @param x The multiplicand\n /// @param y The multiplier\n /// @return z The product of x and y\n function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n unchecked {\n require(x == 0 || (z = x * y) / x == y);\n }\n }\n\n /// @notice Returns x / y, reverts if overflows - no specific check, solidity reverts on division by 0\n /// @param x The numerator\n /// @param y The denominator\n /// @return z The product of x and y\n function div(uint256 x, uint256 y) internal pure returns (uint256 z) {\n return x / y;\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/Pausable.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.10;\n\nimport \"./Context.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract Pausable is Context {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n constructor() {\n _paused = false;\n }\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view virtual returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is not paused.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n modifier whenNotPaused() {\n require(!paused(), \"Pausable: paused\");\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n modifier whenPaused() {\n require(paused(), \"Pausable: not paused\");\n _;\n }\n\n /**\n * @dev Triggers stopped state.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/Ownable.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\nimport \"./Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\ncontract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(\n address indexed previousOwner,\n address indexed newOwner\n );\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor() {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(_owner == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(\n newOwner != address(0),\n \"Ownable: new owner is the zero address\"\n );\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/SafeCast.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)\npragma solidity 0.8.10;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n require(\n value <= type(uint224).max,\n \"SafeCast: value doesn't fit in 224 bits\"\n );\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint184 from uint256, reverting on\n * overflow (when the input is greater than largest uint184).\n *\n * Counterpart to Solidity's `uint184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toUint184(uint256 value) internal pure returns (uint184) {\n require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return uint184(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(\n value <= type(uint128).max,\n \"SafeCast: value doesn't fit in 128 bits\"\n );\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n require(\n value <= type(uint96).max,\n \"SafeCast: value doesn't fit in 96 bits\"\n );\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(\n value <= type(uint64).max,\n \"SafeCast: value doesn't fit in 64 bits\"\n );\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint48 from uint256, reverting on\n * overflow (when the input is greater than largest uint48).\n *\n * Counterpart to Solidity's `uint48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toUint48(uint256 value) internal pure returns (uint48) {\n require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return uint48(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(\n value <= type(uint32).max,\n \"SafeCast: value doesn't fit in 32 bits\"\n );\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(\n value <= type(uint16).max,\n \"SafeCast: value doesn't fit in 16 bits\"\n );\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits.\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(\n value <= type(uint8).max,\n \"SafeCast: value doesn't fit in 8 bits\"\n );\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128) {\n require(\n value >= type(int128).min && value <= type(int128).max,\n \"SafeCast: value doesn't fit in 128 bits\"\n );\n return int128(value);\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64) {\n require(\n value >= type(int64).min && value <= type(int64).max,\n \"SafeCast: value doesn't fit in 64 bits\"\n );\n return int64(value);\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32) {\n require(\n value >= type(int32).min && value <= type(int32).max,\n \"SafeCast: value doesn't fit in 32 bits\"\n );\n return int32(value);\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16) {\n require(\n value >= type(int16).min && value <= type(int16).max,\n \"SafeCast: value doesn't fit in 16 bits\"\n );\n return int16(value);\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits.\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8) {\n require(\n value >= type(int8).min && value <= type(int8).max,\n \"SafeCast: value doesn't fit in 8 bits\"\n );\n return int8(value);\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n require(\n value <= uint256(type(int256).max),\n \"SafeCast: value doesn't fit in an int256\"\n );\n return int256(value);\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/ERC721Enumerable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)\n\npragma solidity ^0.8.10;\n\nimport \"./ERC721.sol\";\nimport \"./IERC721Enumerable.sol\";\n\n/**\n * @dev This implements an optional extension of {ERC721} defined in the EIP that adds\n * enumerability of all the token ids in the contract as well as all token ids owned by each\n * account.\n */\nabstract contract ERC721Enumerable is ERC721, IERC721Enumerable {\n // Mapping from owner to list of owned token IDs\n mapping(address => mapping(uint256 => uint256)) private _ownedTokens;\n\n // Mapping from token ID to index of the owner tokens list\n mapping(uint256 => uint256) private _ownedTokensIndex;\n\n // Array with all token ids, used for enumeration\n uint256[] private _allTokens;\n\n // Mapping from token id to position in the allTokens array\n mapping(uint256 => uint256) private _allTokensIndex;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(ERC721)\n returns (bool)\n {\n return\n interfaceId == type(IERC721Enumerable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index)\n public\n view\n virtual\n override\n returns (uint256)\n {\n require(\n index < ERC721.balanceOf(owner),\n \"ERC721Enumerable: owner index out of bounds\"\n );\n return _ownedTokens[owner][index];\n }\n\n /**\n * @dev See {IERC721Enumerable-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _allTokens.length;\n }\n\n /**\n * @dev See {IERC721Enumerable-tokenByIndex}.\n */\n function tokenByIndex(uint256 index)\n public\n view\n virtual\n override\n returns (uint256)\n {\n require(\n index < ERC721Enumerable.totalSupply(),\n \"ERC721Enumerable: global index out of bounds\"\n );\n return _allTokens[index];\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual override {\n super._beforeTokenTransfer(from, to, tokenId);\n\n if (from == address(0)) {\n _addTokenToAllTokensEnumeration(tokenId);\n } else if (from != to) {\n _removeTokenFromOwnerEnumeration(from, tokenId);\n }\n if (to == address(0)) {\n _removeTokenFromAllTokensEnumeration(tokenId);\n } else if (to != from) {\n _addTokenToOwnerEnumeration(to, tokenId);\n }\n }\n\n /**\n * @dev Private function to add a token to this extension's ownership-tracking data structures.\n * @param to address representing the new owner of the given token ID\n * @param tokenId uint256 ID of the token to be added to the tokens list of the given address\n */\n function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {\n uint256 length = ERC721.balanceOf(to);\n _ownedTokens[to][length] = tokenId;\n _ownedTokensIndex[tokenId] = length;\n }\n\n /**\n * @dev Private function to add a token to this extension's token tracking data structures.\n * @param tokenId uint256 ID of the token to be added to the tokens list\n */\n function _addTokenToAllTokensEnumeration(uint256 tokenId) private {\n _allTokensIndex[tokenId] = _allTokens.length;\n _allTokens.push(tokenId);\n }\n\n /**\n * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that\n * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\n * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\n * This has O(1) time complexity, but alters the order of the _ownedTokens array.\n * @param from address representing the previous owner of the given token ID\n * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\n */\n function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)\n private\n {\n // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;\n uint256 tokenIndex = _ownedTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary\n if (tokenIndex != lastTokenIndex) {\n uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];\n\n _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n }\n\n // This also deletes the contents at the last position of the array\n delete _ownedTokensIndex[tokenId];\n delete _ownedTokens[from][lastTokenIndex];\n }\n\n /**\n * @dev Private function to remove a token from this extension's token tracking data structures.\n * This has O(1) time complexity, but alters the order of the _allTokens array.\n * @param tokenId uint256 ID of the token to be removed from the tokens list\n */\n function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\n // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\n // then delete the last slot (swap and pop).\n\n uint256 lastTokenIndex = _allTokens.length - 1;\n uint256 tokenIndex = _allTokensIndex[tokenId];\n\n // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\n // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\n // an 'if' statement (like in _removeTokenFromOwnerEnumeration)\n uint256 lastTokenId = _allTokens[lastTokenIndex];\n\n _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n\n // This also deletes the contents at the last position of the array\n delete _allTokensIndex[tokenId];\n _allTokens.pop();\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/draft-IERC20Permit.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity 0.8.10;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}" }, "contracts/dependencies/openzeppelin/contracts/ERC721.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)\n\npragma solidity 0.8.10;\n\nimport \"./IERC721.sol\";\nimport \"./IERC721Receiver.sol\";\nimport \"./IERC721Metadata.sol\";\nimport \"./Address.sol\";\nimport \"./Context.sol\";\nimport \"./Strings.sol\";\nimport \"./ERC165.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\n using Address for address;\n using Strings for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override(ERC165)\n returns (bool)\n {\n return\n interfaceId == type(IERC721).interfaceId ||\n interfaceId == type(IERC721Metadata).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner)\n public\n view\n virtual\n override\n returns (uint256)\n {\n require(\n owner != address(0),\n \"ERC721: address zero is not a valid owner\"\n );\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId)\n public\n view\n virtual\n override\n returns (address)\n {\n address owner = _owners[tokenId];\n require(\n owner != address(0),\n \"ERC721: owner query for nonexistent token\"\n );\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId)\n public\n view\n virtual\n override\n returns (string memory)\n {\n require(\n _exists(tokenId),\n \"ERC721Metadata: URI query for nonexistent token\"\n );\n\n string memory baseURI = _baseURI();\n return\n bytes(baseURI).length > 0\n ? string(abi.encodePacked(baseURI, tokenId.toString()))\n : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not owner nor approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId)\n public\n view\n virtual\n override\n returns (address)\n {\n require(\n _exists(tokenId),\n \"ERC721: approved query for nonexistent token\"\n );\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved)\n public\n virtual\n override\n {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator)\n public\n view\n virtual\n override\n returns (bool)\n {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(\n _isApprovedOrOwner(_msgSender(), tokenId),\n \"ERC721: transfer caller is not owner nor approved\"\n );\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) public virtual override {\n require(\n _isApprovedOrOwner(_msgSender(), tokenId),\n \"ERC721: transfer caller is not owner nor approved\"\n );\n _safeTransfer(from, to, tokenId, _data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `_data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(\n _checkOnERC721Received(from, to, tokenId, _data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _owners[tokenId] != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId)\n internal\n view\n virtual\n returns (bool)\n {\n require(\n _exists(tokenId),\n \"ERC721: operator query for nonexistent token\"\n );\n address owner = ERC721.ownerOf(tokenId);\n return (spender == owner ||\n isApprovedForAll(owner, spender) ||\n getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory _data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, _data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Clear approvals\n _approve(address(0), tokenId);\n\n _balances[owner] -= 1;\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(\n ERC721.ownerOf(tokenId) == from,\n \"ERC721: transfer from incorrect owner\"\n );\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Clear approvals from the previous owner\n _approve(address(0), tokenId);\n\n _balances[from] -= 1;\n _balances[to] += 1;\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits a {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits a {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param _data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory _data\n ) private returns (bool) {\n if (to.isContract()) {\n try\n IERC721Receiver(to).onERC721Received(\n _msgSender(),\n from,\n tokenId,\n _data\n )\n returns (bytes4 retval) {\n return retval == IERC721Receiver.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n } else {\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any token transfer. This includes minting\n * and burning.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC721Enumerable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)\n\npragma solidity ^0.8.10;\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n /**\n * @dev Returns the total amount of tokens stored by the contract.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.\n */\n function tokenOfOwnerByIndex(address owner, uint256 index)\n external\n view\n returns (uint256);\n\n /**\n * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n * Use along with {totalSupply} to enumerate all tokens.\n */\n function tokenByIndex(uint256 index) external view returns (uint256);\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC721.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.10;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(\n address indexed from,\n address indexed to,\n uint256 indexed tokenId\n );\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(\n address indexed owner,\n address indexed approved,\n uint256 indexed tokenId\n );\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(\n address indexed owner,\n address indexed operator,\n bool approved\n );\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId)\n external\n view\n returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator)\n external\n view\n returns (bool);\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC721Metadata.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.10;\n\nimport \"./IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" }, "contracts/dependencies/openzeppelin/contracts/Strings.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length)\n internal\n pure\n returns (string memory)\n {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC721Receiver.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)\n\npragma solidity 0.8.10;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" }, "contracts/dependencies/openzeppelin/contracts/ERC165.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId)\n public\n view\n virtual\n override\n returns (bool)\n {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/IERC165.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.10;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 4000 }, "evmVersion": "london", "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} } }