{ "language": "Solidity", "sources": { "contracts/protocol/pool/PoolCore.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {ParaVersionedInitializable} from \"../libraries/paraspace-upgradeability/ParaVersionedInitializable.sol\";\nimport {Errors} from \"../libraries/helpers/Errors.sol\";\nimport {ReserveConfiguration} from \"../libraries/configuration/ReserveConfiguration.sol\";\nimport {PoolLogic} from \"../libraries/logic/PoolLogic.sol\";\nimport {ReserveLogic} from \"../libraries/logic/ReserveLogic.sol\";\nimport {SupplyLogic} from \"../libraries/logic/SupplyLogic.sol\";\nimport {MarketplaceLogic} from \"../libraries/logic/MarketplaceLogic.sol\";\nimport {BorrowLogic} from \"../libraries/logic/BorrowLogic.sol\";\nimport {LiquidationLogic} from \"../libraries/logic/LiquidationLogic.sol\";\nimport {AuctionLogic} from \"../libraries/logic/AuctionLogic.sol\";\nimport {DataTypes} from \"../libraries/types/DataTypes.sol\";\nimport {IERC20WithPermit} from \"../../interfaces/IERC20WithPermit.sol\";\nimport {IPoolAddressesProvider} from \"../../interfaces/IPoolAddressesProvider.sol\";\nimport {IPoolCore} from \"../../interfaces/IPoolCore.sol\";\nimport {INToken} from \"../../interfaces/INToken.sol\";\nimport {IACLManager} from \"../../interfaces/IACLManager.sol\";\nimport {PoolStorage} from \"./PoolStorage.sol\";\nimport {FlashClaimLogic} from \"../libraries/logic/FlashClaimLogic.sol\";\nimport {Address} from \"../../dependencies/openzeppelin/contracts/Address.sol\";\nimport {IERC721Receiver} from \"../../dependencies/openzeppelin/contracts/IERC721Receiver.sol\";\nimport {IMarketplace} from \"../../interfaces/IMarketplace.sol\";\nimport {Errors} from \"../libraries/helpers/Errors.sol\";\nimport {ParaReentrancyGuard} from \"../libraries/paraspace-upgradeability/ParaReentrancyGuard.sol\";\nimport {IAuctionableERC721} from \"../../interfaces/IAuctionableERC721.sol\";\nimport {IReserveAuctionStrategy} from \"../../interfaces/IReserveAuctionStrategy.sol\";\nimport {IWETH} from \"../../misc/interfaces/IWETH.sol\";\n\n/**\n * @title Pool contract\n *\n * @notice Main point of interaction with an ParaSpace protocol's market\n * - Users can:\n * - Supply\n * - Withdraw\n * - Borrow\n * - Repay\n * - Liquidate positions\n * @dev To be covered by a proxy contract, owned by the PoolAddressesProvider of the specific market\n * @dev All admin functions are callable by the PoolConfigurator contract defined also in the\n * PoolAddressesProvider\n **/\ncontract PoolCore is\n ParaVersionedInitializable,\n ParaReentrancyGuard,\n PoolStorage,\n IPoolCore\n{\n using ReserveLogic for DataTypes.ReserveData;\n\n uint256 public constant POOL_REVISION = 120;\n IPoolAddressesProvider public immutable ADDRESSES_PROVIDER;\n\n function getRevision() internal pure virtual override returns (uint256) {\n return POOL_REVISION;\n }\n\n /**\n * @dev Constructor.\n * @param provider The address of the PoolAddressesProvider contract\n */\n constructor(IPoolAddressesProvider provider) {\n ADDRESSES_PROVIDER = provider;\n }\n\n /**\n * @notice Initializes the Pool.\n * @dev Function is invoked by the proxy contract when the Pool contract is added to the\n * PoolAddressesProvider of the market.\n * @dev Caching the address of the PoolAddressesProvider in order to reduce gas consumption on subsequent operations\n * @param provider The address of the PoolAddressesProvider\n **/\n function initialize(IPoolAddressesProvider provider)\n external\n virtual\n initializer\n {\n require(\n provider == ADDRESSES_PROVIDER,\n Errors.INVALID_ADDRESSES_PROVIDER\n );\n\n RGStorage storage rgs = rgStorage();\n\n rgs._status = _NOT_ENTERED;\n }\n\n /// @inheritdoc IPoolCore\n function supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external virtual override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n SupplyLogic.executeSupply(\n ps._reserves,\n ps._usersConfig[onBehalfOf],\n DataTypes.ExecuteSupplyParams({\n asset: asset,\n amount: amount,\n onBehalfOf: onBehalfOf,\n payer: msg.sender,\n referralCode: referralCode\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function supplyERC721(\n address asset,\n DataTypes.ERC721SupplyParams[] calldata tokenData,\n address onBehalfOf,\n uint16 referralCode\n ) external virtual override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n SupplyLogic.executeSupplyERC721(\n ps._reserves,\n ps._usersConfig[onBehalfOf],\n DataTypes.ExecuteSupplyERC721Params({\n asset: asset,\n tokenData: tokenData,\n onBehalfOf: onBehalfOf,\n payer: msg.sender,\n referralCode: referralCode\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function supplyERC721FromNToken(\n address asset,\n DataTypes.ERC721SupplyParams[] calldata tokenData,\n address onBehalfOf\n ) external virtual override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n SupplyLogic.executeSupplyERC721FromNToken(\n ps._reserves,\n ps._usersConfig[onBehalfOf],\n DataTypes.ExecuteSupplyERC721Params({\n asset: asset,\n tokenData: tokenData,\n onBehalfOf: onBehalfOf,\n payer: address(0),\n referralCode: 0\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external virtual override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n // Need to accommodate ERC721 and ERC1155 here\n IERC20WithPermit(asset).permit(\n msg.sender,\n address(this),\n amount,\n deadline,\n permitV,\n permitR,\n permitS\n );\n SupplyLogic.executeSupply(\n ps._reserves,\n ps._usersConfig[onBehalfOf],\n DataTypes.ExecuteSupplyParams({\n asset: asset,\n amount: amount,\n onBehalfOf: onBehalfOf,\n payer: msg.sender,\n referralCode: referralCode\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function withdraw(\n address asset,\n uint256 amount,\n address to\n ) external virtual override nonReentrant returns (uint256) {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return\n SupplyLogic.executeWithdraw(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig[msg.sender],\n DataTypes.ExecuteWithdrawParams({\n asset: asset,\n amount: amount,\n to: to,\n reservesCount: ps._reservesCount,\n oracle: ADDRESSES_PROVIDER.getPriceOracle()\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function withdrawERC721(\n address asset,\n uint256[] calldata tokenIds,\n address to\n ) external virtual override nonReentrant returns (uint256) {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return\n SupplyLogic.executeWithdrawERC721(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig[msg.sender],\n DataTypes.ExecuteWithdrawERC721Params({\n asset: asset,\n tokenIds: tokenIds,\n to: to,\n reservesCount: ps._reservesCount,\n oracle: ADDRESSES_PROVIDER.getPriceOracle()\n })\n );\n }\n\n function decreaseUniswapV3Liquidity(\n address asset,\n uint256 tokenId,\n uint128 liquidityDecrease,\n uint256 amount0Min,\n uint256 amount1Min,\n bool receiveEthAsWeth\n ) external virtual override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return\n SupplyLogic.executeDecreaseUniswapV3Liquidity(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig[msg.sender],\n DataTypes.ExecuteDecreaseUniswapV3LiquidityParams({\n user: msg.sender,\n asset: asset,\n tokenId: tokenId,\n reservesCount: ps._reservesCount,\n liquidityDecrease: liquidityDecrease,\n amount0Min: amount0Min,\n amount1Min: amount1Min,\n receiveEthAsWeth: receiveEthAsWeth,\n oracle: ADDRESSES_PROVIDER.getPriceOracle()\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function borrow(\n address asset,\n uint256 amount,\n uint16 referralCode,\n address onBehalfOf\n ) external virtual override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n BorrowLogic.executeBorrow(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig[onBehalfOf],\n DataTypes.ExecuteBorrowParams({\n asset: asset,\n user: msg.sender,\n onBehalfOf: onBehalfOf,\n amount: amount,\n referralCode: referralCode,\n releaseUnderlying: true,\n reservesCount: ps._reservesCount,\n oracle: ADDRESSES_PROVIDER.getPriceOracle(),\n priceOracleSentinel: ADDRESSES_PROVIDER.getPriceOracleSentinel()\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function repay(\n address asset,\n uint256 amount,\n address onBehalfOf\n ) external virtual override nonReentrant returns (uint256) {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return\n BorrowLogic.executeRepay(\n ps._reserves,\n ps._usersConfig[onBehalfOf],\n DataTypes.ExecuteRepayParams({\n asset: asset,\n amount: amount,\n onBehalfOf: onBehalfOf,\n usePTokens: false\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function repayWithPTokens(address asset, uint256 amount)\n external\n virtual\n override\n nonReentrant\n returns (uint256)\n {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return\n BorrowLogic.executeRepay(\n ps._reserves,\n ps._usersConfig[msg.sender],\n DataTypes.ExecuteRepayParams({\n asset: asset,\n amount: amount,\n onBehalfOf: msg.sender,\n usePTokens: true\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function repayWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external virtual override nonReentrant returns (uint256) {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n {\n IERC20WithPermit(asset).permit(\n msg.sender,\n address(this),\n amount,\n deadline,\n permitV,\n permitR,\n permitS\n );\n }\n {\n DataTypes.ExecuteRepayParams memory params = DataTypes\n .ExecuteRepayParams({\n asset: asset,\n amount: amount,\n onBehalfOf: onBehalfOf,\n usePTokens: false\n });\n return\n BorrowLogic.executeRepay(\n ps._reserves,\n ps._usersConfig[onBehalfOf],\n params\n );\n }\n }\n\n /// @inheritdoc IPoolCore\n function setUserUseERC20AsCollateral(address asset, bool useAsCollateral)\n external\n virtual\n override\n nonReentrant\n {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n SupplyLogic.executeUseERC20AsCollateral(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig[msg.sender],\n asset,\n useAsCollateral,\n ps._reservesCount,\n ADDRESSES_PROVIDER.getPriceOracle()\n );\n }\n\n function setUserUseERC721AsCollateral(\n address asset,\n uint256[] calldata tokenIds,\n bool useAsCollateral\n ) external virtual override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n if (useAsCollateral) {\n SupplyLogic.executeCollateralizeERC721(\n ps._reserves,\n ps._usersConfig[msg.sender],\n asset,\n tokenIds,\n msg.sender\n );\n } else {\n SupplyLogic.executeUncollateralizeERC721(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig[msg.sender],\n asset,\n tokenIds,\n msg.sender,\n ps._reservesCount,\n ADDRESSES_PROVIDER.getPriceOracle()\n );\n }\n }\n\n /// @inheritdoc IPoolCore\n function liquidateERC20(\n address collateralAsset,\n address liquidationAsset,\n address borrower,\n uint256 liquidationAmount,\n bool receivePToken\n ) external payable virtual override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n LiquidationLogic.executeLiquidateERC20(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig,\n DataTypes.ExecuteLiquidateParams({\n reservesCount: ps._reservesCount,\n liquidationAmount: liquidationAmount,\n auctionRecoveryHealthFactor: ps._auctionRecoveryHealthFactor,\n weth: ADDRESSES_PROVIDER.getWETH(),\n collateralAsset: collateralAsset,\n liquidationAsset: liquidationAsset,\n borrower: borrower,\n liquidator: msg.sender,\n receiveXToken: receivePToken,\n priceOracle: ADDRESSES_PROVIDER.getPriceOracle(),\n priceOracleSentinel: ADDRESSES_PROVIDER.getPriceOracleSentinel(),\n collateralTokenId: 0\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function liquidateERC721(\n address collateralAsset,\n address borrower,\n uint256 collateralTokenId,\n uint256 maxLiquidationAmount,\n bool receiveNToken\n ) external payable virtual override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n LiquidationLogic.executeLiquidateERC721(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig,\n DataTypes.ExecuteLiquidateParams({\n reservesCount: ps._reservesCount,\n liquidationAmount: maxLiquidationAmount,\n auctionRecoveryHealthFactor: ps._auctionRecoveryHealthFactor,\n weth: ADDRESSES_PROVIDER.getWETH(),\n collateralAsset: collateralAsset,\n liquidationAsset: ADDRESSES_PROVIDER.getWETH(),\n collateralTokenId: collateralTokenId,\n borrower: borrower,\n liquidator: msg.sender,\n receiveXToken: receiveNToken,\n priceOracle: ADDRESSES_PROVIDER.getPriceOracle(),\n priceOracleSentinel: ADDRESSES_PROVIDER.getPriceOracleSentinel()\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function startAuction(\n address user,\n address collateralAsset,\n uint256 collateralTokenId\n ) external override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n AuctionLogic.executeStartAuction(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig,\n DataTypes.ExecuteAuctionParams({\n reservesCount: ps._reservesCount,\n auctionRecoveryHealthFactor: ps._auctionRecoveryHealthFactor,\n collateralAsset: collateralAsset,\n collateralTokenId: collateralTokenId,\n user: user,\n priceOracle: ADDRESSES_PROVIDER.getPriceOracle()\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function endAuction(\n address user,\n address collateralAsset,\n uint256 collateralTokenId\n ) external override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n AuctionLogic.executeEndAuction(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig,\n DataTypes.ExecuteAuctionParams({\n reservesCount: ps._reservesCount,\n auctionRecoveryHealthFactor: ps._auctionRecoveryHealthFactor,\n collateralAsset: collateralAsset,\n collateralTokenId: collateralTokenId,\n user: user,\n priceOracle: ADDRESSES_PROVIDER.getPriceOracle()\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function flashClaim(\n address receiverAddress,\n address nftAsset,\n uint256[] calldata nftTokenIds,\n bytes calldata params\n ) external virtual override nonReentrant {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n FlashClaimLogic.executeFlashClaim(\n ps,\n DataTypes.ExecuteFlashClaimParams({\n receiverAddress: receiverAddress,\n nftAsset: nftAsset,\n nftTokenIds: nftTokenIds,\n params: params,\n oracle: ADDRESSES_PROVIDER.getPriceOracle()\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function getReserveData(address asset)\n external\n view\n virtual\n override\n returns (DataTypes.ReserveData memory)\n {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return ps._reserves[asset];\n }\n\n /// @inheritdoc IPoolCore\n function getConfiguration(address asset)\n external\n view\n virtual\n override\n returns (DataTypes.ReserveConfigurationMap memory)\n {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return ps._reserves[asset].configuration;\n }\n\n /// @inheritdoc IPoolCore\n function getUserConfiguration(address user)\n external\n view\n virtual\n override\n returns (DataTypes.UserConfigurationMap memory)\n {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return ps._usersConfig[user];\n }\n\n /// @inheritdoc IPoolCore\n function getReserveNormalizedIncome(address asset)\n external\n view\n virtual\n override\n returns (uint256)\n {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return ps._reserves[asset].getNormalizedIncome();\n }\n\n /// @inheritdoc IPoolCore\n function getReserveNormalizedVariableDebt(address asset)\n external\n view\n virtual\n override\n returns (uint256)\n {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return ps._reserves[asset].getNormalizedDebt();\n }\n\n /// @inheritdoc IPoolCore\n function getReservesList()\n external\n view\n virtual\n override\n returns (address[] memory)\n {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n uint256 reservesListCount = ps._reservesCount;\n uint256 droppedReservesCount = 0;\n address[] memory reservesList = new address[](reservesListCount);\n\n for (uint256 i = 0; i < reservesListCount; i++) {\n if (ps._reservesList[i] != address(0)) {\n reservesList[i - droppedReservesCount] = ps._reservesList[i];\n } else {\n droppedReservesCount++;\n }\n }\n\n // Reduces the length of the reserves array by `droppedReservesCount`\n assembly {\n mstore(reservesList, sub(reservesListCount, droppedReservesCount))\n }\n return reservesList;\n }\n\n /// @inheritdoc IPoolCore\n function getReserveAddressById(uint16 id) external view returns (address) {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return ps._reservesList[id];\n }\n\n /// @inheritdoc IPoolCore\n function MAX_NUMBER_RESERVES()\n external\n view\n virtual\n override\n returns (uint16)\n {\n return ReserveConfiguration.MAX_RESERVES_COUNT;\n }\n\n /// @inheritdoc IPoolCore\n function AUCTION_RECOVERY_HEALTH_FACTOR()\n external\n view\n virtual\n override\n returns (uint64)\n {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n return ps._auctionRecoveryHealthFactor;\n }\n\n /// @inheritdoc IPoolCore\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n bool usedAsCollateral,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external virtual override {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n require(\n msg.sender == ps._reserves[asset].xTokenAddress,\n Errors.CALLER_NOT_XTOKEN\n );\n SupplyLogic.executeFinalizeTransferERC20(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig,\n DataTypes.FinalizeTransferParams({\n asset: asset,\n from: from,\n to: to,\n usedAsCollateral: usedAsCollateral,\n amount: amount,\n balanceFromBefore: balanceFromBefore,\n balanceToBefore: balanceToBefore,\n reservesCount: ps._reservesCount,\n oracle: ADDRESSES_PROVIDER.getPriceOracle()\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function finalizeTransferERC721(\n address asset,\n uint256 tokenId,\n address from,\n address to,\n bool usedAsCollateral,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external virtual override {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n require(\n msg.sender == ps._reserves[asset].xTokenAddress,\n Errors.CALLER_NOT_XTOKEN\n );\n SupplyLogic.executeFinalizeTransferERC721(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig,\n DataTypes.FinalizeTransferERC721Params({\n asset: asset,\n from: from,\n to: to,\n usedAsCollateral: usedAsCollateral,\n tokenId: tokenId,\n balanceFromBefore: balanceFromBefore,\n balanceToBefore: balanceToBefore,\n reservesCount: ps._reservesCount,\n oracle: ADDRESSES_PROVIDER.getPriceOracle()\n })\n );\n }\n\n /// @inheritdoc IPoolCore\n function getAuctionData(address ntokenAsset, uint256 tokenId)\n external\n view\n virtual\n override\n returns (DataTypes.AuctionData memory auctionData)\n {\n DataTypes.PoolStorage storage ps = poolStorage();\n\n address underlyingAsset = INToken(ntokenAsset)\n .UNDERLYING_ASSET_ADDRESS();\n DataTypes.ReserveData storage reserve = ps._reserves[underlyingAsset];\n require(\n reserve.id != 0 || ps._reservesList[0] == underlyingAsset,\n Errors.ASSET_NOT_LISTED\n );\n\n if (reserve.auctionStrategyAddress != address(0)) {\n uint256 startTime = IAuctionableERC721(ntokenAsset)\n .getAuctionData(tokenId)\n .startTime;\n IReserveAuctionStrategy auctionStrategy = IReserveAuctionStrategy(\n reserve.auctionStrategyAddress\n );\n\n auctionData.startTime = startTime;\n auctionData.asset = underlyingAsset;\n auctionData.tokenId = tokenId;\n auctionData.currentPriceMultiplier = auctionStrategy\n .calculateAuctionPriceMultiplier(startTime, block.timestamp);\n\n auctionData.maxPriceMultiplier = auctionStrategy\n .getMaxPriceMultiplier();\n auctionData.minExpPriceMultiplier = auctionStrategy\n .getMinExpPriceMultiplier();\n auctionData.minPriceMultiplier = auctionStrategy\n .getMinPriceMultiplier();\n auctionData.stepLinear = auctionStrategy.getStepLinear();\n auctionData.stepExp = auctionStrategy.getStepExp();\n auctionData.tickLength = auctionStrategy.getTickLength();\n }\n }\n\n // This function is necessary when receive erc721 from looksrare\n function onERC721Received(\n address,\n address,\n uint256,\n bytes memory\n ) external virtual returns (bytes4) {\n return this.onERC721Received.selector;\n }\n\n receive() external payable {\n require(\n msg.sender ==\n address(IPoolAddressesProvider(ADDRESSES_PROVIDER).getWETH()),\n \"Receive not allowed\"\n );\n }\n}\n" }, "contracts/interfaces/IERC20WithPermit.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IERC20} from \"../dependencies/openzeppelin/contracts/IERC20.sol\";\n\n/**\n * @title IERC20WithPermit\n *\n * @notice Interface for the permit function (EIP-2612)\n **/\ninterface IERC20WithPermit is IERC20 {\n /**\n * @notice Allow passing a signed message to approve spending\n * @dev implements the permit function as for\n * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md\n * @param owner The owner of the funds\n * @param spender The spender\n * @param value The amount\n * @param deadline The deadline timestamp, type(uint256).max for max deadline\n * @param v Signature param\n * @param s Signature param\n * @param r Signature param\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" }, "contracts/interfaces/IPoolAddressesProvider.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\nimport {IParaProxy} from \"../interfaces/IParaProxy.sol\";\n\n/**\n * @title IPoolAddressesProvider\n *\n * @notice Defines the basic interface for a Pool Addresses Provider.\n **/\ninterface IPoolAddressesProvider {\n /**\n * @dev Emitted when the market identifier is updated.\n * @param oldMarketId The old id of the market\n * @param newMarketId The new id of the market\n */\n event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);\n\n /**\n * @dev Emitted when the pool is updated.\n * @param implementationParams The old address of the Pool\n * @param _init The new address to call upon upgrade\n * @param _calldata The calldata input for the call\n */\n event PoolUpdated(\n IParaProxy.ProxyImplementation[] indexed implementationParams,\n address _init,\n bytes _calldata\n );\n\n /**\n * @dev Emitted when the pool configurator is updated.\n * @param oldAddress The old address of the PoolConfigurator\n * @param newAddress The new address of the PoolConfigurator\n */\n event PoolConfiguratorUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the WETH is updated.\n * @param oldAddress The old address of the WETH\n * @param newAddress The new address of the WETH\n */\n event WETHUpdated(address indexed oldAddress, address indexed newAddress);\n\n /**\n * @dev Emitted when the price oracle is updated.\n * @param oldAddress The old address of the PriceOracle\n * @param newAddress The new address of the PriceOracle\n */\n event PriceOracleUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL manager is updated.\n * @param oldAddress The old address of the ACLManager\n * @param newAddress The new address of the ACLManager\n */\n event ACLManagerUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the ACL admin is updated.\n * @param oldAddress The old address of the ACLAdmin\n * @param newAddress The new address of the ACLAdmin\n */\n event ACLAdminUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the price oracle sentinel is updated.\n * @param oldAddress The old address of the PriceOracleSentinel\n * @param newAddress The new address of the PriceOracleSentinel\n */\n event PriceOracleSentinelUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the pool data provider is updated.\n * @param oldAddress The old address of the PoolDataProvider\n * @param newAddress The new address of the PoolDataProvider\n */\n event ProtocolDataProviderUpdated(\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationAddress The address of the implementation contract\n */\n event ProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n address indexed implementationAddress\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationParams The params of the implementation update\n */\n event ParaProxyCreated(\n bytes32 indexed id,\n address indexed proxyAddress,\n IParaProxy.ProxyImplementation[] indexed implementationParams\n );\n\n /**\n * @dev Emitted when a new proxy is created.\n * @param id The identifier of the proxy\n * @param proxyAddress The address of the created proxy contract\n * @param implementationParams The params of the implementation update\n */\n event ParaProxyUpdated(\n bytes32 indexed id,\n address indexed proxyAddress,\n IParaProxy.ProxyImplementation[] indexed implementationParams\n );\n\n /**\n * @dev Emitted when a new non-proxied contract address is registered.\n * @param id The identifier of the contract\n * @param oldAddress The address of the old contract\n * @param newAddress The address of the new contract\n */\n event AddressSet(\n bytes32 indexed id,\n address indexed oldAddress,\n address indexed newAddress\n );\n\n /**\n * @dev Emitted when the implementation of the proxy registered with id is updated\n * @param id The identifier of the contract\n * @param proxyAddress The address of the proxy contract\n * @param oldImplementationAddress The address of the old implementation contract\n * @param newImplementationAddress The address of the new implementation contract\n */\n event AddressSetAsProxy(\n bytes32 indexed id,\n address indexed proxyAddress,\n address oldImplementationAddress,\n address indexed newImplementationAddress\n );\n\n /**\n * @dev Emitted when the marketplace registered is updated\n * @param id The identifier of the marketplace\n * @param marketplace The address of the marketplace contract\n * @param adapter The address of the marketplace adapter contract\n * @param operator The address of the marketplace transfer helper\n * @param paused Is the marketplace adapter paused\n */\n event MarketplaceUpdated(\n bytes32 indexed id,\n address indexed marketplace,\n address indexed adapter,\n address operator,\n bool paused\n );\n\n /**\n * @notice Returns the id of the ParaSpace market to which this contract points to.\n * @return The market id\n **/\n function getMarketId() external view returns (string memory);\n\n /**\n * @notice Associates an id with a specific PoolAddressesProvider.\n * @dev This can be used to create an onchain registry of PoolAddressesProviders to\n * identify and validate multiple ParaSpace markets.\n * @param newMarketId The market id\n */\n function setMarketId(string calldata newMarketId) external;\n\n /**\n * @notice Returns an address by its identifier.\n * @dev The returned address might be an EOA or a contract, potentially proxied\n * @dev It returns ZERO if there is no registered address with the given id\n * @param id The id\n * @return The address of the registered for the specified id\n */\n function getAddress(bytes32 id) external view returns (address);\n\n /**\n * @notice General function to update the implementation of a proxy registered with\n * certain `id`. If there is no proxy registered, it will instantiate one and\n * set as implementation the `newImplementationAddress`.\n * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit\n * setter function, in order to avoid unexpected consequences\n * @param id The id\n * @param newImplementationAddress The address of the new implementation\n */\n function setAddressAsProxy(bytes32 id, address newImplementationAddress)\n external;\n\n /**\n * @notice Sets an address for an id replacing the address saved in the addresses map.\n * @dev IMPORTANT Use this function carefully, as it will do a hard replacement\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(bytes32 id, address newAddress) external;\n\n /**\n * @notice Returns the address of the Pool proxy.\n * @return The Pool proxy address\n **/\n function getPool() external view returns (address);\n\n /**\n * @notice Updates the implementation of the Pool, or creates a proxy\n * setting the new `pool` implementation when the function is called for the first time.\n * @param implementationParams Contains the implementation addresses and function selectors\n * @param _init The address of the contract or implementation to execute _calldata\n * @param _calldata A function call, including function selector and arguments\n * _calldata is executed with delegatecall on _init\n **/\n function updatePoolImpl(\n IParaProxy.ProxyImplementation[] calldata implementationParams,\n address _init,\n bytes calldata _calldata\n ) external;\n\n /**\n * @notice Returns the address of the PoolConfigurator proxy.\n * @return The PoolConfigurator proxy address\n **/\n function getPoolConfigurator() external view returns (address);\n\n /**\n * @notice Updates the implementation of the PoolConfigurator, or creates a proxy\n * setting the new `PoolConfigurator` implementation when the function is called for the first time.\n * @param newPoolConfiguratorImpl The new PoolConfigurator implementation\n **/\n function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;\n\n /**\n * @notice Returns the address of the price oracle.\n * @return The address of the PriceOracle\n */\n function getPriceOracle() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle.\n * @param newPriceOracle The address of the new PriceOracle\n */\n function setPriceOracle(address newPriceOracle) external;\n\n /**\n * @notice Returns the address of the ACL manager.\n * @return The address of the ACLManager\n */\n function getACLManager() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL manager.\n * @param newAclManager The address of the new ACLManager\n **/\n function setACLManager(address newAclManager) external;\n\n /**\n * @notice Returns the address of the ACL admin.\n * @return The address of the ACL admin\n */\n function getACLAdmin() external view returns (address);\n\n /**\n * @notice Updates the address of the ACL admin.\n * @param newAclAdmin The address of the new ACL admin\n */\n function setACLAdmin(address newAclAdmin) external;\n\n /**\n * @notice Returns the address of the price oracle sentinel.\n * @return The address of the PriceOracleSentinel\n */\n function getPriceOracleSentinel() external view returns (address);\n\n /**\n * @notice Updates the address of the price oracle sentinel.\n * @param newPriceOracleSentinel The address of the new PriceOracleSentinel\n **/\n function setPriceOracleSentinel(address newPriceOracleSentinel) external;\n\n /**\n * @notice Returns the address of the data provider.\n * @return The address of the DataProvider\n */\n function getPoolDataProvider() external view returns (address);\n\n /**\n * @notice Returns the address of the Wrapped ETH.\n * @return The address of the Wrapped ETH\n */\n function getWETH() external view returns (address);\n\n /**\n * @notice Returns the info of the marketplace.\n * @return The info of the marketplace\n */\n function getMarketplace(bytes32 id)\n external\n view\n returns (DataTypes.Marketplace memory);\n\n /**\n * @notice Updates the address of the data provider.\n * @param newDataProvider The address of the new DataProvider\n **/\n function setProtocolDataProvider(address newDataProvider) external;\n\n /**\n * @notice Updates the address of the WETH.\n * @param newWETH The address of the new WETH\n **/\n function setWETH(address newWETH) external;\n\n /**\n * @notice Updates the info of the marketplace.\n * @param marketplace The address of the marketplace\n * @param adapter The contract which handles marketplace logic\n * @param operator The contract which operates users' tokens\n **/\n function setMarketplace(\n bytes32 id,\n address marketplace,\n address adapter,\n address operator,\n bool paused\n ) external;\n}\n" }, "contracts/interfaces/IPoolCore.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolAddressesProvider} from \"./IPoolAddressesProvider.sol\";\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\n\n/**\n * @title IPool\n *\n * @notice Defines the basic interface for an ParaSpace Pool.\n **/\ninterface IPoolCore {\n /**\n * @dev Emitted on supply()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address initiating the supply\n * @param onBehalfOf The beneficiary of the supply, receiving the xTokens\n * @param amount The amount supplied\n * @param referralCode The referral code used\n **/\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n\n event SupplyERC721(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n DataTypes.ERC721SupplyParams[] tokenData,\n uint16 indexed referralCode,\n bool fromNToken\n );\n\n /**\n * @dev Emitted on withdraw()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of xTokens\n * @param to The address that will receive the underlying asset\n * @param amount The amount to be withdrawn\n **/\n event Withdraw(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted on withdrawERC721()\n * @param reserve The address of the underlying asset being withdrawn\n * @param user The address initiating the withdrawal, owner of xTokens\n * @param to The address that will receive the underlying asset\n * @param tokenIds The tokenIds to be withdrawn\n **/\n event WithdrawERC721(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256[] tokenIds\n );\n\n /**\n * @dev Emitted on borrow() and flashLoan() when debt needs to be opened\n * @param reserve The address of the underlying asset being borrowed\n * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just\n * initiator of the transaction on flashLoan()\n * @param onBehalfOf The address that will be getting the debt\n * @param amount The amount borrowed out\n * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray\n * @param referralCode The referral code used\n **/\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n\n /**\n * @dev Emitted on repay()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The beneficiary of the repayment, getting his debt reduced\n * @param repayer The address of the user initiating the repay(), providing the funds\n * @param amount The amount repaid\n * @param usePTokens True if the repayment is done using xTokens, `false` if done with underlying asset directly\n **/\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool usePTokens\n );\n /**\n * @dev Emitted on setUserUseERC20AsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n **/\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted on setUserUseERC20AsCollateral()\n * @param reserve The address of the underlying asset of the reserve\n * @param user The address of the user enabling the usage as collateral\n **/\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n\n /**\n * @dev Emitted when a borrower is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param liquidationAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param borrower The address of the borrower getting liquidated\n * @param liquidationAmount The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralAmount The amount of collateral received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receivePToken True if the liquidators wants to receive the collateral xTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n **/\n event LiquidateERC20(\n address indexed collateralAsset,\n address indexed liquidationAsset,\n address indexed borrower,\n uint256 liquidationAmount,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receivePToken\n );\n\n /**\n * @dev Emitted when a borrower's ERC721 asset is liquidated.\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param liquidationAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param borrower The address of the borrower getting liquidated\n * @param liquidationAmount The debt amount of borrowed `asset` the liquidator wants to cover\n * @param liquidatedCollateralTokenId The token id of ERC721 asset received by the liquidator\n * @param liquidator The address of the liquidator\n * @param receiveNToken True if the liquidators wants to receive the collateral NTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n **/\n event LiquidateERC721(\n address indexed collateralAsset,\n address indexed liquidationAsset,\n address indexed borrower,\n uint256 liquidationAmount,\n uint256 liquidatedCollateralTokenId,\n address liquidator,\n bool receiveNToken\n );\n\n /**\n * @dev Emitted on flashClaim\n * @param target The address of the flash loan receiver contract\n * @param initiator The address initiating the flash claim\n * @param nftAsset address of the underlying asset of NFT\n * @param tokenId The token id of the asset being flash borrowed\n **/\n event FlashClaim(\n address indexed target,\n address indexed initiator,\n address indexed nftAsset,\n uint256 tokenId\n );\n\n /**\n * @dev Allows smart contracts to access the tokens within one transaction, as long as the tokens taken is returned.\n *\n * Requirements:\n * - `nftTokenIds` must exist.\n *\n * @param receiverAddress The address of the contract receiving the tokens, implementing the IFlashClaimReceiver interface\n * @param nftAsset address of the underlying asset of NFT\n * @param nftTokenIds token ids of the underlying asset\n * @param params Variadic packed params to pass to the receiver as extra information\n */\n function flashClaim(\n address receiverAddress,\n address nftAsset,\n uint256[] calldata nftTokenIds,\n bytes calldata params\n ) external;\n\n /**\n * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying xTokens.\n * - E.g. User supplies 100 USDC and gets in return 100 pUSDC\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the xTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of xTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n **/\n function supply(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Supplies multiple `tokenIds` of underlying ERC721 asset into the reserve, receiving in return overlying nTokens.\n * - E.g. User supplies 2 BAYC and gets in return 2 nBAYC\n * @param asset The address of the underlying asset to supply\n * @param tokenData The list of tokenIds and their collateral configs to be supplied\n * @param onBehalfOf The address that will receive the xTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of xTokens\n * is a different wallet\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n **/\n function supplyERC721(\n address asset,\n DataTypes.ERC721SupplyParams[] calldata tokenData,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Same as `supplyERC721` but this can only be called by NToken contract and doesn't require sending the underlying asset.\n * @param asset The address of the underlying asset to supply\n * @param tokenData The list of tokenIds and their collateral configs to be supplied\n * @param onBehalfOf The address that will receive the xTokens\n **/\n function supplyERC721FromNToken(\n address asset,\n DataTypes.ERC721SupplyParams[] calldata tokenData,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Supply with transfer approval of asset to be supplied done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the underlying asset to supply\n * @param amount The amount to be supplied\n * @param onBehalfOf The address that will receive the xTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of xTokens\n * is a different wallet\n * @param deadline The deadline timestamp that the permit is valid\n * @param referralCode Code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n **/\n function supplyWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external;\n\n /**\n * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent xTokens owned\n * E.g. User has 100 pUSDC, calls withdraw() and receives 100 USDC, burning the 100 pUSDC\n * @param asset The address of the underlying asset to withdraw\n * @param amount The underlying amount to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole xToken balance\n * @param to The address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n **/\n function withdraw(\n address asset,\n uint256 amount,\n address to\n ) external returns (uint256);\n\n /**\n * @notice Withdraws multiple `tokenIds` of underlying ERC721 asset from the reserve, burning the equivalent nTokens owned\n * E.g. User has 2 nBAYC, calls withdraw() and receives 2 BAYC, burning the 2 nBAYC\n * @param asset The address of the underlying asset to withdraw\n * @param tokenIds The underlying tokenIds to be withdrawn\n * - Send the value type(uint256).max in order to withdraw the whole xToken balance\n * @param to The address that will receive the underlying, same as msg.sender if the user\n * wants to receive it on his own wallet, or a different address if the beneficiary is a\n * different wallet\n * @return The final amount withdrawn\n **/\n function withdrawERC721(\n address asset,\n uint256[] calldata tokenIds,\n address to\n ) external returns (uint256);\n\n /**\n * @notice Decreases liquidity for underlying Uniswap V3 NFT LP and validates\n * that the user respects liquidation checks.\n * @param asset The asset address of uniswapV3\n * @param tokenId The id of the erc721 token\n * @param liquidityDecrease The amount of liquidity to remove of LP\n * @param amount0Min The minimum amount to remove of token0\n * @param amount1Min The minimum amount to remove of token1\n * @param receiveEthAsWeth If convert weth to ETH\n */\n function decreaseUniswapV3Liquidity(\n address asset,\n uint256 tokenId,\n uint128 liquidityDecrease,\n uint256 amount0Min,\n uint256 amount1Min,\n bool receiveEthAsWeth\n ) external;\n\n /**\n * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already supplied enough collateral, or he was given enough allowance by a credit delegator on the\n * corresponding debt token (VariableDebtToken)\n * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet\n * and 100 stable/variable debt tokens\n * @param asset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param referralCode The code used to register the integrator originating the operation, for potential rewards.\n * 0 if the action is executed directly by the user, without any middle-man\n * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself\n * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator\n * if he has been given credit delegation allowance\n **/\n function borrow(\n address asset,\n uint256 amount,\n uint16 referralCode,\n address onBehalfOf\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned\n * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @return The final amount repaid\n **/\n function repay(\n address asset,\n uint256 amount,\n address onBehalfOf\n ) external returns (uint256);\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve using the reserve xTokens, burning the\n * equivalent debt tokens\n * - E.g. User repays 100 USDC using 100 pUSDC, burning 100 variable/stable debt tokens\n * @dev Passing uint256.max as amount will clean up any residual xToken dust balance, if the user xToken\n * balance is not enough to cover the whole debt\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @return The final amount repaid\n **/\n function repayWithPTokens(address asset, uint256 amount)\n external\n returns (uint256);\n\n /**\n * @notice Repay with transfer approval of asset to be repaid done via permit function\n * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713\n * @param asset The address of the borrowed underlying asset previously borrowed\n * @param amount The amount to repay\n * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`\n * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the\n * user calling the function if he wants to reduce/remove his own debt, or the address of any other\n * other borrower whose debt should be removed\n * @param deadline The deadline timestamp that the permit is valid\n * @param permitV The V parameter of ERC712 permit sig\n * @param permitR The R parameter of ERC712 permit sig\n * @param permitS The S parameter of ERC712 permit sig\n * @return The final amount repaid\n **/\n function repayWithPermit(\n address asset,\n uint256 amount,\n address onBehalfOf,\n uint256 deadline,\n uint8 permitV,\n bytes32 permitR,\n bytes32 permitS\n ) external returns (uint256);\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied asset as collateral\n * @param asset The address of the underlying asset supplied\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n **/\n function setUserUseERC20AsCollateral(address asset, bool useAsCollateral)\n external;\n\n /**\n * @notice Allows suppliers to enable/disable a specific supplied ERC721 asset with a tokenID as collateral\n * @param asset The address of the underlying asset supplied\n * @param tokenIds the ids of the supplied ERC721 token\n * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise\n **/\n function setUserUseERC721AsCollateral(\n address asset,\n uint256[] calldata tokenIds,\n bool useAsCollateral\n ) external;\n\n /**\n * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1\n * - The caller (liquidator) covers `liquidationAmount` amount of debt of the user getting liquidated, and receives\n * a proportionally amount of the `collateralAsset` plus a bonus to cover market risk\n * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation\n * @param liquidationAsset The address of the underlying borrowed asset to be repaid with the liquidation\n * @param user The address of the borrower getting liquidated\n * @param liquidationAmount The debt amount of borrowed `asset` the liquidator wants to cover\n * @param receivePToken True if the liquidators wants to receive the collateral xTokens, `false` if he wants\n * to receive the underlying collateral asset directly\n **/\n function liquidateERC20(\n address collateralAsset,\n address liquidationAsset,\n address user,\n uint256 liquidationAmount,\n bool receivePToken\n ) external payable;\n\n function liquidateERC721(\n address collateralAsset,\n address user,\n uint256 collateralTokenId,\n uint256 liquidationAmount,\n bool receiveNToken\n ) external payable;\n\n /**\n * @notice Start the auction on user's specific NFT collateral\n * @param user The address of the user\n * @param collateralAsset The address of the NFT collateral\n * @param collateralTokenId The tokenId of the NFT collateral\n **/\n function startAuction(\n address user,\n address collateralAsset,\n uint256 collateralTokenId\n ) external;\n\n /**\n * @notice End specific user's auction\n * @param user The address of the user\n * @param collateralAsset The address of the NFT collateral\n * @param collateralTokenId The tokenId of the NFT collateral\n **/\n function endAuction(\n address user,\n address collateralAsset,\n uint256 collateralTokenId\n ) external;\n\n /**\n * @notice Returns the configuration of the user across all the reserves\n * @param user The user address\n * @return The configuration of the user\n **/\n function getUserConfiguration(address user)\n external\n view\n returns (DataTypes.UserConfigurationMap memory);\n\n /**\n * @notice Returns the configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The configuration of the reserve\n **/\n function getConfiguration(address asset)\n external\n view\n returns (DataTypes.ReserveConfigurationMap memory);\n\n /**\n * @notice Returns the normalized income normalized income of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve's normalized income\n */\n function getReserveNormalizedIncome(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the normalized variable debt per unit of asset\n * @param asset The address of the underlying asset of the reserve\n * @return The reserve normalized variable debt\n */\n function getReserveNormalizedVariableDebt(address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the state and configuration of the reserve\n * @param asset The address of the underlying asset of the reserve\n * @return The state and configuration data of the reserve\n **/\n function getReserveData(address asset)\n external\n view\n returns (DataTypes.ReserveData memory);\n\n /**\n * @notice Validates and finalizes an PToken transfer\n * @dev Only callable by the overlying xToken of the `asset`\n * @param asset The address of the underlying asset of the xToken\n * @param from The user from which the xTokens are transferred\n * @param to The user receiving the xTokens\n * @param amount The amount being transferred/withdrawn\n * @param balanceFromBefore The xToken balance of the `from` user before the transfer\n * @param balanceToBefore The xToken balance of the `to` user before the transfer\n */\n function finalizeTransfer(\n address asset,\n address from,\n address to,\n bool usedAsCollateral,\n uint256 amount,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Validates and finalizes an NToken transfer\n * @dev Only callable by the overlying xToken of the `asset`\n * @param asset The address of the underlying asset of the xToken\n * @param tokenId The tokenId of the ERC721 asset\n * @param from The user from which the xTokens are transferred\n * @param to The user receiving the xTokens\n * @param balanceFromBefore The xToken balance of the `from` user before the transfer\n * @param balanceToBefore The xToken balance of the `to` user before the transfer\n */\n function finalizeTransferERC721(\n address asset,\n uint256 tokenId,\n address from,\n address to,\n bool usedAsCollateral,\n uint256 balanceFromBefore,\n uint256 balanceToBefore\n ) external;\n\n /**\n * @notice Returns the list of the underlying assets of all the initialized reserves\n * @dev It does not include dropped reserves\n * @return The addresses of the underlying assets of the initialized reserves\n **/\n function getReservesList() external view returns (address[] memory);\n\n /**\n * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct\n * @param id The id of the reserve as stored in the DataTypes.ReserveData struct\n * @return The address of the reserve associated with id\n **/\n function getReserveAddressById(uint16 id) external view returns (address);\n\n /**\n * @notice Returns the auction related data of specific asset collection and token id.\n * @param ntokenAsset The address of ntoken\n * @param tokenId The token id which is currently auctioned for liquidation\n * @return The auction related data of the corresponding (ntokenAsset, tokenId)\n */\n function getAuctionData(address ntokenAsset, uint256 tokenId)\n external\n view\n returns (DataTypes.AuctionData memory);\n\n // function getAuctionData(address user, address) external view returns (DataTypes.AuctionData memory);\n /**\n * @notice Returns the PoolAddressesProvider connected to this contract\n * @return The address of the PoolAddressesProvider\n **/\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Returns the maximum number of reserves supported to be listed in this Pool\n * @return The maximum number of reserves supported\n */\n function MAX_NUMBER_RESERVES() external view returns (uint16);\n\n /**\n * @notice Returns the auction recovery health factor\n * @return The auction recovery health factor\n */\n function AUCTION_RECOVERY_HEALTH_FACTOR() external view returns (uint64);\n}\n" }, "contracts/interfaces/INToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IERC721} from \"../dependencies/openzeppelin/contracts/IERC721.sol\";\nimport {IERC721Receiver} from \"../dependencies/openzeppelin/contracts/IERC721Receiver.sol\";\nimport {IERC721Enumerable} from \"../dependencies/openzeppelin/contracts/IERC721Enumerable.sol\";\nimport {IERC1155Receiver} from \"../dependencies/openzeppelin/contracts/IERC1155Receiver.sol\";\n\nimport {IInitializableNToken} from \"./IInitializableNToken.sol\";\nimport {IXTokenType} from \"./IXTokenType.sol\";\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\n\n/**\n * @title INToken\n * @author ParallelFi\n * @notice Defines the basic interface for an NToken.\n **/\ninterface INToken is\n IERC721Enumerable,\n IInitializableNToken,\n IERC721Receiver,\n IERC1155Receiver,\n IXTokenType\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 * @dev Emitted during rescueERC721()\n * @param token The address of the token\n * @param to The address of the recipient\n * @param ids The ids of the tokens being rescued\n **/\n event RescueERC721(\n address indexed token,\n address indexed to,\n uint256[] ids\n );\n\n /**\n * @dev Emitted during RescueERC1155()\n * @param token The address of the token\n * @param to The address of the recipient\n * @param ids The ids of the tokens being rescued\n * @param amounts The amount of NFTs being rescued for a specific id.\n * @param data The data of the tokens that is being rescued. Usually this is 0.\n **/\n event RescueERC1155(\n address indexed token,\n address indexed to,\n uint256[] ids,\n uint256[] amounts,\n bytes data\n );\n\n /**\n * @dev Emitted during executeAirdrop()\n * @param airdropContract The address of the airdrop contract\n **/\n event ExecuteAirdrop(address indexed airdropContract);\n\n /**\n * @notice Mints `amount` nTokens to `user`\n * @param onBehalfOf The address of the user that will receive the minted nTokens\n * @param tokenData The list of the tokens getting minted and their collateral configs\n * @return old and new collateralized balance\n */\n function mint(\n address onBehalfOf,\n DataTypes.ERC721SupplyParams[] calldata tokenData\n ) external returns (uint64, uint64);\n\n /**\n * @notice Burns nTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`\n * @dev In some instances, the mint event could be emitted from a burn transaction\n * if the amount to burn is less than the interest that the user accrued\n * @param from The address from which the nTokens will be burned\n * @param receiverOfUnderlying The address that will receive the underlying\n * @param tokenIds The ids of the tokens getting burned\n * @return old and new collateralized balance\n **/\n function burn(\n address from,\n address receiverOfUnderlying,\n uint256[] calldata tokenIds\n ) external returns (uint64, uint64);\n\n // TODO are we using the Treasury at all? Can we remove?\n // /**\n // * @notice Mints nTokens to the reserve treasury\n // * @param tokenId The id of the token getting minted\n // * @param index The next liquidity index of the reserve\n // */\n // function mintToTreasury(uint256 tokenId, uint256 index) external;\n\n /**\n * @notice Transfers nTokens in the event of a borrow being liquidated, in case the liquidators reclaims the nToken\n * @param from The address getting liquidated, current owner of the nTokens\n * @param to The recipient\n * @param tokenId The id of the token getting transferred\n **/\n function transferOnLiquidation(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @notice Transfers the underlying asset to `target`.\n * @dev Used by the Pool to transfer assets in borrow(), withdraw() and flashLoan()\n * @param user The recipient of the underlying\n * @param tokenId The id of the token getting transferred\n **/\n function transferUnderlyingTo(address user, uint256 tokenId) external;\n\n /**\n * @notice Handles the underlying received by the nToken after the transfer has been completed.\n * @dev The default implementation is empty as with standard ERC721 tokens, nothing needs to be done after the\n * transfer is concluded. However in the future there may be nTokens that allow for example to stake the underlying\n * to receive LM rewards. In that case, `handleRepayment()` would perform the staking of the underlying asset.\n * @param user The user executing the repayment\n * @param tokenId The amount getting repaid\n **/\n function handleRepayment(address user, uint256 tokenId) external;\n\n /**\n * @notice Returns the address of the underlying asset of this nToken (E.g. WETH for pWETH)\n * @return The address of the underlying asset\n **/\n function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n\n /**\n * @notice Rescue ERC20 Token.\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 function rescueERC20(\n address token,\n address to,\n uint256 amount\n ) external;\n\n /**\n * @notice Rescue ERC721 Token.\n * @param token The address of the token\n * @param to The address of the recipient\n * @param ids The ids of the tokens being rescued\n **/\n function rescueERC721(\n address token,\n address to,\n uint256[] calldata ids\n ) external;\n\n /**\n * @notice Rescue ERC1155 Token.\n * @param token The address of the token\n * @param to The address of the recipient\n * @param ids The ids of the tokens being rescued\n * @param amounts The amount of NFTs being rescued for a specific id.\n * @param data The data of the tokens that is being rescued. Usually this is 0.\n **/\n function rescueERC1155(\n address token,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n\n /**\n * @notice Executes airdrop.\n * @param airdropContract The address of the airdrop contract\n * @param airdropParams Third party airdrop abi data. You need to get this from the third party airdrop.\n **/\n function executeAirdrop(\n address airdropContract,\n bytes calldata airdropParams\n ) external;\n\n function getAtomicPricingConfig() external view returns (bool);\n}\n" }, "contracts/interfaces/IACLManager.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolAddressesProvider} from \"./IPoolAddressesProvider.sol\";\n\n/**\n * @title IACLManager\n *\n * @notice Defines the basic interface for the ACL Manager\n **/\ninterface IACLManager {\n /**\n * @notice Returns the contract address of the PoolAddressesProvider\n * @return The address of the PoolAddressesProvider\n */\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Returns the identifier of the PoolAdmin role\n * @return The id of the PoolAdmin role\n */\n function POOL_ADMIN_ROLE() external view returns (bytes32);\n\n /**\n * @notice Returns the identifier of the EmergencyAdmin role\n * @return The id of the EmergencyAdmin role\n */\n function EMERGENCY_ADMIN_ROLE() external view returns (bytes32);\n\n /**\n * @notice Returns the identifier of the RiskAdmin role\n * @return The id of the RiskAdmin role\n */\n function RISK_ADMIN_ROLE() external view returns (bytes32);\n\n /**\n * @notice Returns the identifier of the FlashBorrower role\n * @return The id of the FlashBorrower role\n */\n function FLASH_BORROWER_ROLE() external view returns (bytes32);\n\n /**\n * @notice Returns the identifier of the Bridge role\n * @return The id of the Bridge role\n */\n function BRIDGE_ROLE() external view returns (bytes32);\n\n /**\n * @notice Returns the identifier of the AssetListingAdmin role\n * @return The id of the AssetListingAdmin role\n */\n function ASSET_LISTING_ADMIN_ROLE() external view returns (bytes32);\n\n /**\n * @notice Set the role as admin of a specific role.\n * @dev By default the admin role for all roles is `DEFAULT_ADMIN_ROLE`.\n * @param role The role to be managed by the admin role\n * @param adminRole The admin role\n */\n function setRoleAdmin(bytes32 role, bytes32 adminRole) external;\n\n /**\n * @notice Adds a new admin as PoolAdmin\n * @param admin The address of the new admin\n */\n function addPoolAdmin(address admin) external;\n\n /**\n * @notice Removes an admin as PoolAdmin\n * @param admin The address of the admin to remove\n */\n function removePoolAdmin(address admin) external;\n\n /**\n * @notice Returns true if the address is PoolAdmin, false otherwise\n * @param admin The address to check\n * @return True if the given address is PoolAdmin, false otherwise\n */\n function isPoolAdmin(address admin) external view returns (bool);\n\n /**\n * @notice Adds a new admin as EmergencyAdmin\n * @param admin The address of the new admin\n */\n function addEmergencyAdmin(address admin) external;\n\n /**\n * @notice Removes an admin as EmergencyAdmin\n * @param admin The address of the admin to remove\n */\n function removeEmergencyAdmin(address admin) external;\n\n /**\n * @notice Returns true if the address is EmergencyAdmin, false otherwise\n * @param admin The address to check\n * @return True if the given address is EmergencyAdmin, false otherwise\n */\n function isEmergencyAdmin(address admin) external view returns (bool);\n\n /**\n * @notice Adds a new admin as RiskAdmin\n * @param admin The address of the new admin\n */\n function addRiskAdmin(address admin) external;\n\n /**\n * @notice Removes an admin as RiskAdmin\n * @param admin The address of the admin to remove\n */\n function removeRiskAdmin(address admin) external;\n\n /**\n * @notice Returns true if the address is RiskAdmin, false otherwise\n * @param admin The address to check\n * @return True if the given address is RiskAdmin, false otherwise\n */\n function isRiskAdmin(address admin) external view returns (bool);\n\n /**\n * @notice Adds a new address as FlashBorrower\n * @param borrower The address of the new FlashBorrower\n */\n function addFlashBorrower(address borrower) external;\n\n /**\n * @notice Removes an admin as FlashBorrower\n * @param borrower The address of the FlashBorrower to remove\n */\n function removeFlashBorrower(address borrower) external;\n\n /**\n * @notice Returns true if the address is FlashBorrower, false otherwise\n * @param borrower The address to check\n * @return True if the given address is FlashBorrower, false otherwise\n */\n function isFlashBorrower(address borrower) external view returns (bool);\n\n /**\n * @notice Adds a new address as Bridge\n * @param bridge The address of the new Bridge\n */\n function addBridge(address bridge) external;\n\n /**\n * @notice Removes an address as Bridge\n * @param bridge The address of the bridge to remove\n */\n function removeBridge(address bridge) external;\n\n /**\n * @notice Returns true if the address is Bridge, false otherwise\n * @param bridge The address to check\n * @return True if the given address is Bridge, false otherwise\n */\n function isBridge(address bridge) external view returns (bool);\n\n /**\n * @notice Adds a new admin as AssetListingAdmin\n * @param admin The address of the new admin\n */\n function addAssetListingAdmin(address admin) external;\n\n /**\n * @notice Removes an admin as AssetListingAdmin\n * @param admin The address of the admin to remove\n */\n function removeAssetListingAdmin(address admin) external;\n\n /**\n * @notice Returns true if the address is AssetListingAdmin, false otherwise\n * @param admin The address to check\n * @return True if the given address is AssetListingAdmin, false otherwise\n */\n function isAssetListingAdmin(address admin) external view returns (bool);\n}\n" }, "contracts/interfaces/IMarketplace.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\nimport {Errors} from \"../protocol/libraries/helpers/Errors.sol\";\nimport {OrderTypes} from \"../dependencies/looksrare/contracts/libraries/OrderTypes.sol\";\nimport {SeaportInterface} from \"../dependencies/seaport/contracts/interfaces/SeaportInterface.sol\";\nimport {ILooksRareExchange} from \"../dependencies/looksrare/contracts/interfaces/ILooksRareExchange.sol\";\nimport {SignatureChecker} from \"../dependencies/looksrare/contracts/libraries/SignatureChecker.sol\";\nimport {ConsiderationItem} from \"../dependencies/seaport/contracts/lib/ConsiderationStructs.sol\";\nimport {AdvancedOrder, CriteriaResolver, Fulfillment, OfferItem, ItemType} from \"../dependencies/seaport/contracts/lib/ConsiderationStructs.sol\";\nimport {Address} from \"../dependencies/openzeppelin/contracts/Address.sol\";\nimport {IERC1271} from \"../dependencies/openzeppelin/contracts/IERC1271.sol\";\n\ninterface IMarketplace {\n function getAskOrderInfo(bytes memory data, address WETH)\n external\n view\n returns (DataTypes.OrderInfo memory orderInfo);\n\n function getBidOrderInfo(bytes memory data)\n external\n view\n returns (DataTypes.OrderInfo memory orderInfo);\n\n function matchAskWithTakerBid(\n address marketplace,\n bytes calldata data,\n uint256 value\n ) external payable returns (bytes memory);\n\n function matchBidWithTakerAsk(address marketplace, bytes calldata data)\n external\n returns (bytes memory);\n}\n" }, "contracts/interfaces/IAuctionableERC721.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\n\n/**\n * @title IAuctionableERC721\n * @author Parallel\n * @notice Defines the basic interface for an AuctionableERC721.\n **/\ninterface IAuctionableERC721 {\n /**\n * @dev get the auction configuration of a specific token\n */\n function isAuctioned(uint256 tokenId) external view returns (bool);\n\n /**\n *\n * @dev start auction\n */\n function startAuction(uint256 tokenId) external;\n\n /**\n *\n * @dev end auction\n */\n function endAuction(uint256 tokenId) external;\n\n /**\n *\n * @dev get auction data\n */\n function getAuctionData(uint256 tokenId)\n external\n view\n returns (DataTypes.Auction memory);\n}\n" }, "contracts/interfaces/IReserveAuctionStrategy.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title IReserveAuctionStrategy\n *\n * @notice Interface for the calculation of current auction price\n */\ninterface IReserveAuctionStrategy {\n function getMaxPriceMultiplier() external view returns (uint256);\n\n function getMinExpPriceMultiplier() external view returns (uint256);\n\n function getMinPriceMultiplier() external view returns (uint256);\n\n function getStepLinear() external view returns (uint256);\n\n function getStepExp() external view returns (uint256);\n\n function getTickLength() external view returns (uint256);\n\n /**\n * @notice Calculates the interest rates depending on the reserve's state and configurations\n * @param auctionStartTimestamp The auction start block timestamp\n * @param currentTimestamp The current block timestamp\n * @return auctionPrice The current auction price\n **/\n function calculateAuctionPriceMultiplier(\n uint256 auctionStartTimestamp,\n uint256 currentTimestamp\n ) external view returns (uint256);\n}\n" }, "contracts/protocol/pool/PoolStorage.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {UserConfiguration} from \"../libraries/configuration/UserConfiguration.sol\";\nimport {ReserveConfiguration} from \"../libraries/configuration/ReserveConfiguration.sol\";\nimport {ReserveLogic} from \"../libraries/logic/ReserveLogic.sol\";\nimport {DataTypes} from \"../libraries/types/DataTypes.sol\";\n\n/**\n * @title PoolStorage\n *\n * @notice Contract used as storage of the Pool contract.\n * @dev It defines the storage layout of the Pool contract.\n */\ncontract PoolStorage {\n bytes32 constant POOL_STORAGE_POSITION =\n bytes32(uint256(keccak256(\"paraspace.proxy.pool.storage\")) - 1);\n\n function poolStorage()\n internal\n pure\n returns (DataTypes.PoolStorage storage rgs)\n {\n bytes32 position = POOL_STORAGE_POSITION;\n assembly {\n rgs.slot := position\n }\n }\n}\n" }, "contracts/misc/interfaces/IWETH.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.10;\n\ninterface IWETH {\n function deposit() external payable;\n\n function withdraw(uint256) external;\n\n function approve(address guy, uint256 wad) external returns (bool);\n\n function transferFrom(\n address src,\n address dst,\n uint256 wad\n ) external returns (bool);\n}\n" }, "contracts/protocol/libraries/paraspace-upgradeability/ParaVersionedInitializable.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title VersionedInitializable\n * , inspired by the OpenZeppelin Initializable contract\n * @notice Helper contract to implement initializer functions. To use it, replace\n * the constructor with a function that has the `initializer` modifier.\n * @dev WARNING: Unlike constructors, initializer functions must be manually\n * invoked. This applies both to deploying an Initializable contract, as well\n * as extending an Initializable contract via inheritance.\n * WARNING: When used with inheritance, manual care must be taken to not invoke\n * a parent initializer twice, or ensure that all initializers are idempotent,\n * because this is not dealt with automatically as with constructors.\n */\nabstract contract ParaVersionedInitializable {\n bytes32 constant VERSION_STORAGE_POSITION =\n bytes32(uint256(keccak256(\"paraspace.proxy.version.storage\")) - 1);\n\n struct VersionStorage {\n /**\n * @dev Indicates that the contract has been initialized.\n */\n uint256 lastInitializedRevision;\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool initializing;\n }\n\n function versionStorage()\n internal\n pure\n returns (VersionStorage storage vs)\n {\n bytes32 position = VERSION_STORAGE_POSITION;\n assembly {\n vs.slot := position\n }\n }\n\n /**\n * @dev Modifier to use in the initializer function of a contract.\n */\n modifier initializer() {\n VersionStorage storage vs = versionStorage();\n\n uint256 revision = getRevision();\n require(\n vs.initializing ||\n isConstructor() ||\n revision > vs.lastInitializedRevision,\n \"Contract instance has already been initialized\"\n );\n\n bool isTopLevelCall = !vs.initializing;\n if (isTopLevelCall) {\n vs.initializing = true;\n vs.lastInitializedRevision = revision;\n }\n\n _;\n\n if (isTopLevelCall) {\n vs.initializing = false;\n }\n }\n\n /**\n * @notice Returns the revision number of the contract\n * @dev Needs to be defined in the inherited class as a constant.\n * @return The revision number\n **/\n function getRevision() internal pure virtual returns (uint256);\n\n /**\n * @notice Returns true if and only if the function is running in the constructor\n * @return True if the function is running in the constructor\n **/\n function isConstructor() private view returns (bool) {\n // extcodesize checks the size of the code stored in an address, and\n // address returns the current address. Since the code is still not\n // deployed when running a constructor, any checks on its code size will\n // yield zero, making it an effective way to detect if a contract is\n // under construction or not.\n uint256 cs;\n //solium-disable-next-line\n assembly {\n cs := extcodesize(address())\n }\n return cs == 0;\n }\n\n // Reserved storage space to allow for layout changes in the future.\n // uint256[50] private ______gap;\n}\n" }, "contracts/protocol/libraries/helpers/Errors.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\n/**\n * @title Errors library\n *\n * @notice Defines the error messages emitted by the different contracts of the ParaSpace protocol\n */\nlibrary Errors {\n string public constant CALLER_NOT_POOL_ADMIN = \"1\"; // 'The caller of the function is not a pool admin'\n string public constant CALLER_NOT_EMERGENCY_ADMIN = \"2\"; // 'The caller of the function is not an emergency admin'\n string public constant CALLER_NOT_POOL_OR_EMERGENCY_ADMIN = \"3\"; // 'The caller of the function is not a pool or emergency admin'\n string public constant CALLER_NOT_RISK_OR_POOL_ADMIN = \"4\"; // 'The caller of the function is not a risk or pool admin'\n string public constant CALLER_NOT_ASSET_LISTING_OR_POOL_ADMIN = \"5\"; // 'The caller of the function is not an asset listing or pool admin'\n string public constant CALLER_NOT_BRIDGE = \"6\"; // 'The caller of the function is not a bridge'\n string public constant ADDRESSES_PROVIDER_NOT_REGISTERED = \"7\"; // 'Pool addresses provider is not registered'\n string public constant INVALID_ADDRESSES_PROVIDER_ID = \"8\"; // 'Invalid id for the pool addresses provider'\n string public constant NOT_CONTRACT = \"9\"; // 'Address is not a contract'\n string public constant CALLER_NOT_POOL_CONFIGURATOR = \"10\"; // 'The caller of the function is not the pool configurator'\n string public constant CALLER_NOT_XTOKEN = \"11\"; // 'The caller of the function is not an PToken or NToken'\n string public constant INVALID_ADDRESSES_PROVIDER = \"12\"; // 'The address of the pool addresses provider is invalid'\n string public constant RESERVE_ALREADY_ADDED = \"14\"; // 'Reserve has already been added to reserve list'\n string public constant NO_MORE_RESERVES_ALLOWED = \"15\"; // 'Maximum amount of reserves in the pool reached'\n string public constant RESERVE_LIQUIDITY_NOT_ZERO = \"18\"; // 'The liquidity of the reserve needs to be 0'\n string public constant INVALID_RESERVE_PARAMS = \"20\"; // 'Invalid risk parameters for the reserve'\n string public constant CALLER_MUST_BE_POOL = \"23\"; // 'The caller of this function must be a pool'\n string public constant INVALID_MINT_AMOUNT = \"24\"; // 'Invalid amount to mint'\n string public constant INVALID_BURN_AMOUNT = \"25\"; // 'Invalid amount to burn'\n string public constant INVALID_AMOUNT = \"26\"; // 'Amount must be greater than 0'\n string public constant RESERVE_INACTIVE = \"27\"; // 'Action requires an active reserve'\n string public constant RESERVE_FROZEN = \"28\"; // 'Action cannot be performed because the reserve is frozen'\n string public constant RESERVE_PAUSED = \"29\"; // 'Action cannot be performed because the reserve is paused'\n string public constant BORROWING_NOT_ENABLED = \"30\"; // 'Borrowing is not enabled'\n string public constant STABLE_BORROWING_NOT_ENABLED = \"31\"; // 'Stable borrowing is not enabled'\n string public constant NOT_ENOUGH_AVAILABLE_USER_BALANCE = \"32\"; // 'User cannot withdraw more than the available balance'\n string public constant INVALID_INTEREST_RATE_MODE_SELECTED = \"33\"; // 'Invalid interest rate mode selected'\n string public constant COLLATERAL_BALANCE_IS_ZERO = \"34\"; // 'The collateral balance is 0'\n string public constant HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD =\n \"35\"; // 'Health factor is lesser than the liquidation threshold'\n string public constant COLLATERAL_CANNOT_COVER_NEW_BORROW = \"36\"; // 'There is not enough collateral to cover a new borrow'\n string public constant COLLATERAL_SAME_AS_BORROWING_CURRENCY = \"37\"; // 'Collateral is (mostly) the same currency that is being borrowed'\n string public constant AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = \"38\"; // 'The requested amount is greater than the max loan size in stable rate mode'\n string public constant NO_DEBT_OF_SELECTED_TYPE = \"39\"; // 'For repayment of a specific type of debt, the user needs to have debt that type'\n string public constant NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = \"40\"; // 'To repay on behalf of a user an explicit amount to repay is needed'\n string public constant NO_OUTSTANDING_STABLE_DEBT = \"41\"; // 'User does not have outstanding stable rate debt on this reserve'\n string public constant NO_OUTSTANDING_VARIABLE_DEBT = \"42\"; // 'User does not have outstanding variable rate debt on this reserve'\n string public constant UNDERLYING_BALANCE_ZERO = \"43\"; // 'The underlying balance needs to be greater than 0'\n string public constant INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = \"44\"; // 'Interest rate rebalance conditions were not met'\n string public constant HEALTH_FACTOR_NOT_BELOW_THRESHOLD = \"45\"; // 'Health factor is not below the threshold'\n string public constant COLLATERAL_CANNOT_BE_AUCTIONED_OR_LIQUIDATED = \"46\"; // 'The collateral chosen cannot be auctioned OR liquidated'\n string public constant SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = \"47\"; // 'User did not borrow the specified currency'\n string public constant SAME_BLOCK_BORROW_REPAY = \"48\"; // 'Borrow and repay in same block is not allowed'\n string public constant BORROW_CAP_EXCEEDED = \"50\"; // 'Borrow cap is exceeded'\n string public constant SUPPLY_CAP_EXCEEDED = \"51\"; // 'Supply cap is exceeded'\n string public constant XTOKEN_SUPPLY_NOT_ZERO = \"54\"; // 'PToken supply is not zero'\n string public constant STABLE_DEBT_NOT_ZERO = \"55\"; // 'Stable debt supply is not zero'\n string public constant VARIABLE_DEBT_SUPPLY_NOT_ZERO = \"56\"; // 'Variable debt supply is not zero'\n string public constant LTV_VALIDATION_FAILED = \"57\"; // 'Ltv validation failed'\n string public constant PRICE_ORACLE_SENTINEL_CHECK_FAILED = \"59\"; // 'Price oracle sentinel validation failed'\n string public constant RESERVE_ALREADY_INITIALIZED = \"61\"; // 'Reserve has already been initialized'\n string public constant INVALID_LTV = \"63\"; // 'Invalid ltv parameter for the reserve'\n string public constant INVALID_LIQ_THRESHOLD = \"64\"; // 'Invalid liquidity threshold parameter for the reserve'\n string public constant INVALID_LIQ_BONUS = \"65\"; // 'Invalid liquidity bonus parameter for the reserve'\n string public constant INVALID_DECIMALS = \"66\"; // 'Invalid decimals parameter of the underlying asset of the reserve'\n string public constant INVALID_RESERVE_FACTOR = \"67\"; // 'Invalid reserve factor parameter for the reserve'\n string public constant INVALID_BORROW_CAP = \"68\"; // 'Invalid borrow cap for the reserve'\n string public constant INVALID_SUPPLY_CAP = \"69\"; // 'Invalid supply cap for the reserve'\n string public constant INVALID_LIQUIDATION_PROTOCOL_FEE = \"70\"; // 'Invalid liquidation protocol fee for the reserve'\n string public constant INVALID_DEBT_CEILING = \"73\"; // 'Invalid debt ceiling for the reserve\n string public constant INVALID_RESERVE_INDEX = \"74\"; // 'Invalid reserve index'\n string public constant ACL_ADMIN_CANNOT_BE_ZERO = \"75\"; // 'ACL admin cannot be set to the zero address'\n string public constant INCONSISTENT_PARAMS_LENGTH = \"76\"; // 'Array parameters that should be equal length are not'\n string public constant ZERO_ADDRESS_NOT_VALID = \"77\"; // 'Zero address not valid'\n string public constant INVALID_EXPIRATION = \"78\"; // 'Invalid expiration'\n string public constant INVALID_SIGNATURE = \"79\"; // 'Invalid signature'\n string public constant OPERATION_NOT_SUPPORTED = \"80\"; // 'Operation not supported'\n string public constant ASSET_NOT_LISTED = \"82\"; // 'Asset is not listed'\n string public constant INVALID_OPTIMAL_USAGE_RATIO = \"83\"; // 'Invalid optimal usage ratio'\n string public constant INVALID_OPTIMAL_STABLE_TO_TOTAL_DEBT_RATIO = \"84\"; // 'Invalid optimal stable to total debt ratio'\n string public constant UNDERLYING_CANNOT_BE_RESCUED = \"85\"; // 'The underlying asset cannot be rescued'\n string public constant ADDRESSES_PROVIDER_ALREADY_ADDED = \"86\"; // 'Reserve has already been added to reserve list'\n string public constant POOL_ADDRESSES_DO_NOT_MATCH = \"87\"; // 'The token implementation pool address and the pool address provided by the initializing pool do not match'\n string public constant STABLE_BORROWING_ENABLED = \"88\"; // 'Stable borrowing is enabled'\n string public constant SILOED_BORROWING_VIOLATION = \"89\"; // 'User is trying to borrow multiple assets including a siloed one'\n string public constant RESERVE_DEBT_NOT_ZERO = \"90\"; // the total debt of the reserve needs to be 0\n string public constant NOT_THE_OWNER = \"91\"; // user is not the owner of a given asset\n string public constant LIQUIDATION_AMOUNT_NOT_ENOUGH = \"92\";\n string public constant INVALID_ASSET_TYPE = \"93\"; // invalid asset type for action.\n string public constant INVALID_FLASH_CLAIM_RECEIVER = \"94\"; // invalid flash claim receiver.\n string public constant ERC721_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = \"95\"; // ERC721 Health factor is not below the threshold. Can only liquidate ERC20.\n string public constant UNDERLYING_ASSET_CAN_NOT_BE_TRANSFERRED = \"96\"; //underlying asset can not be transferred.\n string public constant TOKEN_TRANSFERRED_CAN_NOT_BE_SELF_ADDRESS = \"97\"; //token transferred can not be self address.\n string public constant INVALID_AIRDROP_CONTRACT_ADDRESS = \"98\"; //invalid airdrop contract address.\n string public constant INVALID_AIRDROP_PARAMETERS = \"99\"; //invalid airdrop parameters.\n string public constant CALL_AIRDROP_METHOD_FAILED = \"100\"; //call airdrop method failed.\n string public constant SUPPLIER_NOT_NTOKEN = \"101\"; //supplier is not the NToken contract\n string public constant CALL_MARKETPLACE_FAILED = \"102\"; //call marketplace failed.\n string public constant INVALID_MARKETPLACE_ID = \"103\"; //invalid marketplace id.\n string public constant INVALID_MARKETPLACE_ORDER = \"104\"; //invalid marketplace id.\n string public constant CREDIT_DOES_NOT_MATCH_ORDER = \"105\"; //credit doesn't match order.\n string public constant PAYNOW_NOT_ENOUGH = \"106\"; //paynow not enough.\n string public constant INVALID_CREDIT_SIGNATURE = \"107\"; //invalid credit signature.\n string public constant INVALID_ORDER_TAKER = \"108\"; //invalid order taker.\n string public constant MARKETPLACE_PAUSED = \"109\"; //marketplace paused.\n string public constant INVALID_AUCTION_RECOVERY_HEALTH_FACTOR = \"110\"; //invalid auction recovery health factor.\n string public constant AUCTION_ALREADY_STARTED = \"111\"; //auction already started.\n string public constant AUCTION_NOT_STARTED = \"112\"; //auction not started yet.\n string public constant AUCTION_NOT_ENABLED = \"113\"; //auction not enabled on the reserve.\n string public constant ERC721_HEALTH_FACTOR_NOT_ABOVE_THRESHOLD = \"114\"; //ERC721 Health factor is not above the threshold.\n string public constant TOKEN_IN_AUCTION = \"115\"; //tokenId is in auction.\n string public constant AUCTIONED_BALANCE_NOT_ZERO = \"116\"; //auctioned balance not zero.\n string public constant LIQUIDATOR_CAN_NOT_BE_SELF = \"117\"; //user can not liquidate himself.\n string public constant INVALID_RECIPIENT = \"118\"; //invalid recipient specified in order.\n string public constant UNIV3_NOT_ALLOWED = \"119\"; //flash claim is not allowed for UniswapV3.\n string public constant NTOKEN_BALANCE_EXCEEDED = \"120\"; //ntoken balance exceed limit.\n string public constant ORACLE_PRICE_NOT_READY = \"121\"; //oracle price not ready.\n string public constant SET_ORACLE_SOURCE_NOT_ALLOWED = \"122\"; //source of oracle not allowed to set.\n string public constant INVALID_LIQUIDATION_ASSET = \"123\"; //invalid liquidation asset.\n string public constant ONLY_UNIV3_ALLOWED = \"124\"; //only UniswapV3 allowed.\n string public constant GLOBAL_DEBT_IS_ZERO = \"125\"; //liquidation is not allowed when global debt is zero.\n string public constant ORACLE_PRICE_EXPIRED = \"126\"; //oracle price expired.\n string public constant APE_STAKING_POSITION_EXISTED = \"127\"; //ape staking position is existed.\n string public constant SAPE_NOT_ALLOWED = \"128\"; //operation is not allow for sApe.\n string public constant TOTAL_STAKING_AMOUNT_WRONG = \"129\"; //cash plus borrow amount not equal to total staking amount.\n string public constant APE_STAKING_AMOUNT_NON_ZERO = \"130\"; //ape staking amount should be zero when supply bayc/mayc.\n}\n" }, "contracts/protocol/libraries/configuration/ReserveConfiguration.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\n\n/**\n * @title ReserveConfiguration library\n *\n * @notice Implements the bitmap logic to handle the reserve configuration\n */\nlibrary ReserveConfiguration {\n uint256 internal constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore\n uint256 internal constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore\n uint256 internal constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore\n uint256 internal constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant PAUSED_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant SILOED_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant BORROW_CAP_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000FFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant SUPPLY_CAP_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFF000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant LIQUIDATION_PROTOCOL_FEE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n uint256 internal constant ASSET_TYPE_MASK = 0xFFFFFFFFFFFFFFFFFFFFF0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n //uint256 internal constant DYNAMIC_CONFIGS_MASK = 0xFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // prettier-ignore\n\n /// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed\n uint256 internal constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;\n uint256 internal constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;\n uint256 internal constant RESERVE_DECIMALS_START_BIT_POSITION = 48;\n uint256 internal constant IS_ACTIVE_START_BIT_POSITION = 56;\n uint256 internal constant IS_FROZEN_START_BIT_POSITION = 57;\n uint256 internal constant BORROWING_ENABLED_START_BIT_POSITION = 58;\n uint256 internal constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;\n uint256 internal constant IS_PAUSED_START_BIT_POSITION = 60;\n uint256 internal constant SILOED_BORROWING_START_BIT_POSITION = 62;\n /// @dev bit 63 reserved\n\n uint256 internal constant RESERVE_FACTOR_START_BIT_POSITION = 64;\n uint256 internal constant BORROW_CAP_START_BIT_POSITION = 80;\n uint256 internal constant SUPPLY_CAP_START_BIT_POSITION = 116;\n uint256 internal constant LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION = 152;\n uint256 internal constant ASSET_TYPE_START_BIT_POSITION = 168;\n\n uint256 internal constant MAX_VALID_LTV = 65535;\n uint256 internal constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;\n uint256 internal constant MAX_VALID_LIQUIDATION_BONUS = 65535;\n uint256 internal constant MAX_VALID_DECIMALS = 255;\n uint256 internal constant MAX_VALID_RESERVE_FACTOR = 65535;\n uint256 internal constant MAX_VALID_BORROW_CAP = 68719476735;\n uint256 internal constant MAX_VALID_SUPPLY_CAP = 68719476735;\n uint256 internal constant MAX_VALID_LIQUIDATION_PROTOCOL_FEE = 65535;\n uint256 internal constant MAX_ASSET_TYPE = 16;\n\n uint16 public constant MAX_RESERVES_COUNT = 128;\n\n /**\n * @notice Sets the Loan to Value of the reserve\n * @param self The reserve configuration\n * @param ltv The new ltv\n **/\n function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv)\n internal\n pure\n {\n require(ltv <= MAX_VALID_LTV, Errors.INVALID_LTV);\n\n self.data = (self.data & LTV_MASK) | ltv;\n }\n\n /**\n * @notice Gets the Loan to Value of the reserve\n * @param self The reserve configuration\n * @return The loan to value\n **/\n function getLtv(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (uint256)\n {\n return self.data & ~LTV_MASK;\n }\n\n /**\n * @notice Sets the liquidation threshold of the reserve\n * @param self The reserve configuration\n * @param threshold The new liquidation threshold\n **/\n function setLiquidationThreshold(\n DataTypes.ReserveConfigurationMap memory self,\n uint256 threshold\n ) internal pure {\n require(\n threshold <= MAX_VALID_LIQUIDATION_THRESHOLD,\n Errors.INVALID_LIQ_THRESHOLD\n );\n\n self.data =\n (self.data & LIQUIDATION_THRESHOLD_MASK) |\n (threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the liquidation threshold of the reserve\n * @param self The reserve configuration\n * @return The liquidation threshold\n **/\n function getLiquidationThreshold(\n DataTypes.ReserveConfigurationMap memory self\n ) internal pure returns (uint256) {\n return\n (self.data & ~LIQUIDATION_THRESHOLD_MASK) >>\n LIQUIDATION_THRESHOLD_START_BIT_POSITION;\n }\n\n /**\n * @notice Sets the liquidation bonus of the reserve\n * @param self The reserve configuration\n * @param bonus The new liquidation bonus\n **/\n function setLiquidationBonus(\n DataTypes.ReserveConfigurationMap memory self,\n uint256 bonus\n ) internal pure {\n require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.INVALID_LIQ_BONUS);\n\n self.data =\n (self.data & LIQUIDATION_BONUS_MASK) |\n (bonus << LIQUIDATION_BONUS_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the liquidation bonus of the reserve\n * @param self The reserve configuration\n * @return The liquidation bonus\n **/\n function getLiquidationBonus(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (uint256)\n {\n return\n (self.data & ~LIQUIDATION_BONUS_MASK) >>\n LIQUIDATION_BONUS_START_BIT_POSITION;\n }\n\n /**\n * @notice Sets the decimals of the underlying asset of the reserve\n * @param self The reserve configuration\n * @param decimals The decimals\n **/\n function setDecimals(\n DataTypes.ReserveConfigurationMap memory self,\n uint256 decimals\n ) internal pure {\n require(decimals <= MAX_VALID_DECIMALS, Errors.INVALID_DECIMALS);\n\n self.data =\n (self.data & DECIMALS_MASK) |\n (decimals << RESERVE_DECIMALS_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the decimals of the underlying asset of the reserve\n * @param self The reserve configuration\n * @return The decimals of the asset\n **/\n function getDecimals(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (uint256)\n {\n return\n (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;\n }\n\n /**\n * @notice Sets the asset type of the reserve\n * @param self The reserve configuration\n * @param assetType The asset type\n **/\n function setAssetType(\n DataTypes.ReserveConfigurationMap memory self,\n DataTypes.AssetType assetType\n ) internal pure {\n require(\n uint256(assetType) <= MAX_ASSET_TYPE,\n Errors.INVALID_ASSET_TYPE\n );\n\n self.data =\n (self.data & ASSET_TYPE_MASK) |\n (uint256(assetType) << ASSET_TYPE_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the asset type of the reserve\n * @param self The reserve configuration\n * @return The asset type\n **/\n function getAssetType(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (DataTypes.AssetType)\n {\n return\n DataTypes.AssetType(\n (self.data & ~ASSET_TYPE_MASK) >> ASSET_TYPE_START_BIT_POSITION\n );\n }\n\n /**\n * @notice Sets the active state of the reserve\n * @param self The reserve configuration\n * @param active The active state\n **/\n function setActive(\n DataTypes.ReserveConfigurationMap memory self,\n bool active\n ) internal pure {\n self.data =\n (self.data & ACTIVE_MASK) |\n (uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the active state of the reserve\n * @param self The reserve configuration\n * @return The active state\n **/\n function getActive(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (bool)\n {\n return (self.data & ~ACTIVE_MASK) != 0;\n }\n\n /**\n * @notice Sets the frozen state of the reserve\n * @param self The reserve configuration\n * @param frozen The frozen state\n **/\n function setFrozen(\n DataTypes.ReserveConfigurationMap memory self,\n bool frozen\n ) internal pure {\n self.data =\n (self.data & FROZEN_MASK) |\n (uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the frozen state of the reserve\n * @param self The reserve configuration\n * @return The frozen state\n **/\n function getFrozen(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (bool)\n {\n return (self.data & ~FROZEN_MASK) != 0;\n }\n\n /**\n * @notice Sets the paused state of the reserve\n * @param self The reserve configuration\n * @param paused The paused state\n **/\n function setPaused(\n DataTypes.ReserveConfigurationMap memory self,\n bool paused\n ) internal pure {\n self.data =\n (self.data & PAUSED_MASK) |\n (uint256(paused ? 1 : 0) << IS_PAUSED_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the paused state of the reserve\n * @param self The reserve configuration\n * @return The paused state\n **/\n function getPaused(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (bool)\n {\n return (self.data & ~PAUSED_MASK) != 0;\n }\n\n /**\n * @notice Sets the siloed borrowing flag for the reserve.\n * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset.\n * @param self The reserve configuration\n * @param siloed True if the asset is siloed\n **/\n function setSiloedBorrowing(\n DataTypes.ReserveConfigurationMap memory self,\n bool siloed\n ) internal pure {\n self.data =\n (self.data & SILOED_BORROWING_MASK) |\n (uint256(siloed ? 1 : 0) << SILOED_BORROWING_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the siloed borrowing flag for the reserve.\n * @dev When this flag is set to true, users borrowing this asset will not be allowed to borrow any other asset.\n * @param self The reserve configuration\n * @return The siloed borrowing flag\n **/\n function getSiloedBorrowing(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (bool)\n {\n return (self.data & ~SILOED_BORROWING_MASK) != 0;\n }\n\n /**\n * @notice Enables or disables borrowing on the reserve\n * @param self The reserve configuration\n * @param enabled True if the borrowing needs to be enabled, false otherwise\n **/\n function setBorrowingEnabled(\n DataTypes.ReserveConfigurationMap memory self,\n bool enabled\n ) internal pure {\n self.data =\n (self.data & BORROWING_MASK) |\n (uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the borrowing state of the reserve\n * @param self The reserve configuration\n * @return The borrowing state\n **/\n function getBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (bool)\n {\n return (self.data & ~BORROWING_MASK) != 0;\n }\n\n /**\n * @notice Sets the reserve factor of the reserve\n * @param self The reserve configuration\n * @param reserveFactor The reserve factor\n **/\n function setReserveFactor(\n DataTypes.ReserveConfigurationMap memory self,\n uint256 reserveFactor\n ) internal pure {\n require(\n reserveFactor <= MAX_VALID_RESERVE_FACTOR,\n Errors.INVALID_RESERVE_FACTOR\n );\n\n self.data =\n (self.data & RESERVE_FACTOR_MASK) |\n (reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the reserve factor of the reserve\n * @param self The reserve configuration\n * @return The reserve factor\n **/\n function getReserveFactor(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (uint256)\n {\n return\n (self.data & ~RESERVE_FACTOR_MASK) >>\n RESERVE_FACTOR_START_BIT_POSITION;\n }\n\n /**\n * @notice Sets the borrow cap of the reserve\n * @param self The reserve configuration\n * @param borrowCap The borrow cap\n **/\n function setBorrowCap(\n DataTypes.ReserveConfigurationMap memory self,\n uint256 borrowCap\n ) internal pure {\n require(borrowCap <= MAX_VALID_BORROW_CAP, Errors.INVALID_BORROW_CAP);\n\n self.data =\n (self.data & BORROW_CAP_MASK) |\n (borrowCap << BORROW_CAP_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the borrow cap of the reserve\n * @param self The reserve configuration\n * @return The borrow cap\n **/\n function getBorrowCap(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (uint256)\n {\n return (self.data & ~BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION;\n }\n\n /**\n * @notice Sets the supply cap of the reserve\n * @param self The reserve configuration\n * @param supplyCap The supply cap\n **/\n function setSupplyCap(\n DataTypes.ReserveConfigurationMap memory self,\n uint256 supplyCap\n ) internal pure {\n require(supplyCap <= MAX_VALID_SUPPLY_CAP, Errors.INVALID_SUPPLY_CAP);\n\n self.data =\n (self.data & SUPPLY_CAP_MASK) |\n (supplyCap << SUPPLY_CAP_START_BIT_POSITION);\n }\n\n /**\n * @notice Gets the supply cap of the reserve\n * @param self The reserve configuration\n * @return The supply cap\n **/\n function getSupplyCap(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (uint256)\n {\n return (self.data & ~SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION;\n }\n\n /**\n * @notice Sets the liquidation protocol fee of the reserve\n * @param self The reserve configuration\n * @param liquidationProtocolFee The liquidation protocol fee\n **/\n function setLiquidationProtocolFee(\n DataTypes.ReserveConfigurationMap memory self,\n uint256 liquidationProtocolFee\n ) internal pure {\n require(\n liquidationProtocolFee <= MAX_VALID_LIQUIDATION_PROTOCOL_FEE,\n Errors.INVALID_LIQUIDATION_PROTOCOL_FEE\n );\n\n self.data =\n (self.data & LIQUIDATION_PROTOCOL_FEE_MASK) |\n (liquidationProtocolFee <<\n LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION);\n }\n\n /**\n * @dev Gets the liquidation protocol fee\n * @param self The reserve configuration\n * @return The liquidation protocol fee\n **/\n function getLiquidationProtocolFee(\n DataTypes.ReserveConfigurationMap memory self\n ) internal pure returns (uint256) {\n return\n (self.data & ~LIQUIDATION_PROTOCOL_FEE_MASK) >>\n LIQUIDATION_PROTOCOL_FEE_START_BIT_POSITION;\n }\n\n /**\n * @notice Gets the configuration flags of the reserve\n * @param self The reserve configuration\n * @return The state flag representing active\n * @return The state flag representing frozen\n * @return The state flag representing borrowing enabled\n * @return The state flag representing paused\n * @return The asset type\n **/\n function getFlags(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (\n bool,\n bool,\n bool,\n bool,\n DataTypes.AssetType\n )\n {\n uint256 dataLocal = self.data;\n\n return (\n (dataLocal & ~ACTIVE_MASK) != 0,\n (dataLocal & ~FROZEN_MASK) != 0,\n (dataLocal & ~BORROWING_MASK) != 0,\n (dataLocal & ~PAUSED_MASK) != 0,\n DataTypes.AssetType(\n (dataLocal & ~ASSET_TYPE_MASK) >> ASSET_TYPE_START_BIT_POSITION\n )\n );\n }\n\n /**\n * @notice Gets the configuration parameters of the reserve from storage\n * @param self The reserve configuration\n * @return The state param representing ltv\n * @return The state param representing liquidation threshold\n * @return The state param representing liquidation bonus\n * @return The state param representing reserve decimals\n * @return The state param representing reserve factor\n **/\n function getParams(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (\n uint256,\n uint256,\n uint256,\n uint256,\n uint256\n )\n {\n uint256 dataLocal = self.data;\n\n return (\n dataLocal & ~LTV_MASK,\n (dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >>\n LIQUIDATION_THRESHOLD_START_BIT_POSITION,\n (dataLocal & ~LIQUIDATION_BONUS_MASK) >>\n LIQUIDATION_BONUS_START_BIT_POSITION,\n (dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,\n (dataLocal & ~RESERVE_FACTOR_MASK) >>\n RESERVE_FACTOR_START_BIT_POSITION\n );\n }\n\n /**\n * @notice Gets the caps parameters of the reserve from storage\n * @param self The reserve configuration\n * @return The state param representing borrow cap\n * @return The state param representing supply cap.\n **/\n function getCaps(DataTypes.ReserveConfigurationMap memory self)\n internal\n pure\n returns (uint256, uint256)\n {\n uint256 dataLocal = self.data;\n\n return (\n (dataLocal & ~BORROW_CAP_MASK) >> BORROW_CAP_START_BIT_POSITION,\n (dataLocal & ~SUPPLY_CAP_MASK) >> SUPPLY_CAP_START_BIT_POSITION\n );\n }\n}\n" }, "contracts/protocol/libraries/logic/PoolLogic.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {GPv2SafeERC20} from \"../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol\";\nimport {Address} from \"../../../dependencies/openzeppelin/contracts/Address.sol\";\nimport {IERC20} from \"../../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {IERC721} from \"../../../dependencies/openzeppelin/contracts/IERC721.sol\";\nimport {IPToken} from \"../../../interfaces/IPToken.sol\";\nimport {ReserveConfiguration} from \"../configuration/ReserveConfiguration.sol\";\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {WadRayMath} from \"../math/WadRayMath.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {ReserveLogic} from \"./ReserveLogic.sol\";\nimport {ValidationLogic} from \"./ValidationLogic.sol\";\nimport {GenericLogic} from \"./GenericLogic.sol\";\nimport {IXTokenType, XTokenType} from \"../../../interfaces/IXTokenType.sol\";\n\n/**\n * @title PoolLogic library\n *\n * @notice Implements the logic for Pool specific functions\n */\nlibrary PoolLogic {\n using GPv2SafeERC20 for IERC20;\n using WadRayMath for uint256;\n using ReserveLogic for DataTypes.ReserveData;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n // See `IPool` for descriptions\n event MintedToTreasury(address indexed reserve, uint256 amountMinted);\n\n /**\n * @notice Initialize an asset reserve and add the reserve to the list of reserves\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param params Additional parameters needed for initiation\n * @return true if appended, false if inserted at existing empty spot\n **/\n function executeInitReserve(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.InitReserveParams memory params\n ) external returns (bool) {\n if (params.asset != DataTypes.SApeAddress) {\n require(Address.isContract(params.asset), Errors.NOT_CONTRACT);\n }\n reservesData[params.asset].init(\n params.xTokenAddress,\n params.variableDebtAddress,\n params.interestRateStrategyAddress,\n params.auctionStrategyAddress\n );\n\n bool reserveAlreadyAdded = reservesData[params.asset].id != 0 ||\n reservesList[0] == params.asset;\n require(!reserveAlreadyAdded, Errors.RESERVE_ALREADY_ADDED);\n\n for (uint16 i = 0; i < params.reservesCount; i++) {\n if (reservesList[i] == address(0)) {\n reservesData[params.asset].id = i;\n reservesList[i] = params.asset;\n return false;\n }\n }\n\n require(\n params.reservesCount < params.maxNumberReserves,\n Errors.NO_MORE_RESERVES_ALLOWED\n );\n reservesData[params.asset].id = params.reservesCount;\n reservesList[params.reservesCount] = params.asset;\n return true;\n }\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param assetType The asset type of the token\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amountOrTokenId The amount or id of token to transfer\n */\n function executeRescueTokens(\n DataTypes.AssetType assetType,\n address token,\n address to,\n uint256 amountOrTokenId\n ) external {\n if (assetType == DataTypes.AssetType.ERC20) {\n IERC20(token).safeTransfer(to, amountOrTokenId);\n } else if (assetType == DataTypes.AssetType.ERC721) {\n IERC721(token).safeTransferFrom(address(this), to, amountOrTokenId);\n }\n }\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of xTokens\n * @param reservesData The state of all the reserves\n * @param assets The list of reserves for which the minting needs to be executed\n **/\n function executeMintToTreasury(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n address[] calldata assets\n ) external {\n for (uint256 i = 0; i < assets.length; i++) {\n address assetAddress = assets[i];\n\n DataTypes.ReserveData storage reserve = reservesData[assetAddress];\n\n DataTypes.ReserveConfigurationMap\n memory reserveConfiguration = reserve.configuration;\n\n // this cover both inactive reserves and invalid reserves since the flag will be 0 for both\n if (\n !reserveConfiguration.getActive() ||\n reserveConfiguration.getAssetType() != DataTypes.AssetType.ERC20\n ) {\n continue;\n }\n\n uint256 accruedToTreasury = reserve.accruedToTreasury;\n\n if (accruedToTreasury != 0) {\n reserve.accruedToTreasury = 0;\n uint256 normalizedIncome = reserve.getNormalizedIncome();\n uint256 amountToMint = accruedToTreasury.rayMul(\n normalizedIncome\n );\n IPToken(reserve.xTokenAddress).mintToTreasury(\n amountToMint,\n normalizedIncome\n );\n\n emit MintedToTreasury(assetAddress, amountToMint);\n }\n }\n }\n\n /**\n * @notice Drop a reserve\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param asset The address of the underlying asset of the reserve\n **/\n function executeDropReserve(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n address asset\n ) external {\n DataTypes.ReserveData storage reserve = reservesData[asset];\n ValidationLogic.validateDropReserve(reservesList, reserve, asset);\n reservesList[reservesData[asset].id] = address(0);\n delete reservesData[asset];\n }\n\n /**\n * @notice Returns the user account data across all the reserves\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n * @return erc721HealthFactor The current erc721 health factor of the user\n **/\n function executeGetUserAccountData(\n address user,\n DataTypes.PoolStorage storage ps,\n address oracle\n )\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor,\n uint256 erc721HealthFactor\n )\n {\n DataTypes.CalculateUserAccountDataParams memory params = DataTypes\n .CalculateUserAccountDataParams({\n userConfig: ps._usersConfig[user],\n reservesCount: ps._reservesCount,\n user: user,\n oracle: oracle\n });\n\n (\n totalCollateralBase,\n ,\n totalDebtBase,\n ltv,\n currentLiquidationThreshold,\n ,\n ,\n healthFactor,\n erc721HealthFactor,\n\n ) = GenericLogic.calculateUserAccountData(\n ps._reserves,\n ps._reservesList,\n params\n );\n\n availableBorrowsBase = GenericLogic.calculateAvailableBorrows(\n totalCollateralBase,\n totalDebtBase,\n ltv\n );\n }\n\n function executeGetAssetLtvAndLT(\n DataTypes.PoolStorage storage ps,\n address asset,\n uint256 tokenId\n ) external view returns (uint256 ltv, uint256 lt) {\n DataTypes.ReserveData storage assetReserve = ps._reserves[asset];\n DataTypes.ReserveConfigurationMap memory assetConfig = assetReserve\n .configuration;\n (uint256 collectionLtv, uint256 collectionLT, , , ) = assetConfig\n .getParams();\n XTokenType tokenType = IXTokenType(assetReserve.xTokenAddress)\n .getXTokenType();\n if (tokenType == XTokenType.NTokenUniswapV3) {\n return\n GenericLogic.getLtvAndLTForUniswapV3(\n ps._reserves,\n asset,\n tokenId,\n collectionLtv,\n collectionLT\n );\n } else {\n return (collectionLtv, collectionLT);\n }\n }\n}\n" }, "contracts/protocol/libraries/logic/ReserveLogic.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {IERC20} from \"../../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {GPv2SafeERC20} from \"../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol\";\nimport {IVariableDebtToken} from \"../../../interfaces/IVariableDebtToken.sol\";\nimport {IReserveInterestRateStrategy} from \"../../../interfaces/IReserveInterestRateStrategy.sol\";\nimport {ReserveConfiguration} from \"../configuration/ReserveConfiguration.sol\";\nimport {MathUtils} from \"../math/MathUtils.sol\";\nimport {WadRayMath} from \"../math/WadRayMath.sol\";\nimport {PercentageMath} from \"../math/PercentageMath.sol\";\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {SafeCast} from \"../../../dependencies/openzeppelin/contracts/SafeCast.sol\";\n\n/**\n * @title ReserveLogic library\n *\n * @notice Implements the logic to update the reserves state\n */\nlibrary ReserveLogic {\n using WadRayMath for uint256;\n using PercentageMath for uint256;\n using SafeCast for uint256;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n // See `IPool` for descriptions\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @notice Returns the ongoing normalized income for the reserve.\n * @dev A value of 1e27 means there is no income. As time passes, the income is accrued\n * @dev A value of 2*1e27 means for each unit of asset one unit of income has been accrued\n * @param reserve The reserve object\n * @return The normalized income, expressed in ray\n **/\n function getNormalizedIncome(DataTypes.ReserveData storage reserve)\n internal\n view\n returns (uint256)\n {\n uint40 timestamp = reserve.lastUpdateTimestamp;\n\n //solium-disable-next-line\n if (timestamp == block.timestamp) {\n //if the index was updated in the same block, no need to perform any calculation\n return reserve.liquidityIndex;\n } else {\n return\n MathUtils\n .calculateLinearInterest(\n reserve.currentLiquidityRate,\n timestamp\n )\n .rayMul(reserve.liquidityIndex);\n }\n }\n\n /**\n * @notice Returns the ongoing normalized variable debt for the reserve.\n * @dev A value of 1e27 means there is no debt. As time passes, the debt is accrued\n * @dev A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated\n * @param reserve The reserve object\n * @return The normalized variable debt, expressed in ray\n **/\n function getNormalizedDebt(DataTypes.ReserveData storage reserve)\n internal\n view\n returns (uint256)\n {\n uint40 timestamp = reserve.lastUpdateTimestamp;\n\n //solium-disable-next-line\n if (timestamp == block.timestamp) {\n //if the index was updated in the same block, no need to perform any calculation\n return reserve.variableBorrowIndex;\n } else {\n return\n MathUtils\n .calculateCompoundedInterest(\n reserve.currentVariableBorrowRate,\n timestamp\n )\n .rayMul(reserve.variableBorrowIndex);\n }\n }\n\n /**\n * @notice Updates the liquidity cumulative index and the variable borrow index.\n * @param reserve The reserve object\n * @param reserveCache The caching layer for the reserve data\n **/\n function updateState(\n DataTypes.ReserveData storage reserve,\n DataTypes.ReserveCache memory reserveCache\n ) internal {\n _updateIndexes(reserve, reserveCache);\n _accrueToTreasury(reserve, reserveCache);\n }\n\n /**\n * @notice Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example\n * to accumulate the flashloan fee to the reserve, and spread it between all the suppliers.\n * @param reserve The reserve object\n * @param totalLiquidity The total liquidity available in the reserve\n * @param amount The amount to accumulate\n * @return The next liquidity index of the reserve\n **/\n function cumulateToLiquidityIndex(\n DataTypes.ReserveData storage reserve,\n uint256 totalLiquidity,\n uint256 amount\n ) internal returns (uint256) {\n //next liquidity index is calculated this way: `((amount / totalLiquidity) + 1) * liquidityIndex`\n //division `amount / totalLiquidity` done in ray for precision\n uint256 result = (amount.wadToRay().rayDiv(totalLiquidity.wadToRay()) +\n WadRayMath.RAY).rayMul(reserve.liquidityIndex);\n reserve.liquidityIndex = result.toUint128();\n return result;\n }\n\n /**\n * @notice Initializes a reserve.\n * @param reserve The reserve object\n * @param xTokenAddress The address of the overlying xtoken contract\n * @param variableDebtTokenAddress The address of the overlying variable debt token contract\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n **/\n function init(\n DataTypes.ReserveData storage reserve,\n address xTokenAddress,\n address variableDebtTokenAddress,\n address interestRateStrategyAddress,\n address auctionStrategyAddress\n ) internal {\n require(\n reserve.xTokenAddress == address(0),\n Errors.RESERVE_ALREADY_INITIALIZED\n );\n\n reserve.liquidityIndex = uint128(WadRayMath.RAY);\n reserve.variableBorrowIndex = uint128(WadRayMath.RAY);\n reserve.xTokenAddress = xTokenAddress;\n reserve.variableDebtTokenAddress = variableDebtTokenAddress;\n reserve.interestRateStrategyAddress = interestRateStrategyAddress;\n reserve.auctionStrategyAddress = auctionStrategyAddress;\n }\n\n struct UpdateInterestRatesLocalVars {\n uint256 nextLiquidityRate;\n uint256 nextVariableRate;\n uint256 totalVariableDebt;\n }\n\n /**\n * @notice Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate.\n * @param reserve The reserve reserve to be updated\n * @param reserveCache The caching layer for the reserve data\n * @param reserveAddress The address of the reserve to be updated\n * @param liquidityAdded The amount of liquidity added to the protocol (supply or repay) in the previous action\n * @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)\n **/\n function updateInterestRates(\n DataTypes.ReserveData storage reserve,\n DataTypes.ReserveCache memory reserveCache,\n address reserveAddress,\n uint256 liquidityAdded,\n uint256 liquidityTaken\n ) internal {\n UpdateInterestRatesLocalVars memory vars;\n\n vars.totalVariableDebt = reserveCache.nextScaledVariableDebt.rayMul(\n reserveCache.nextVariableBorrowIndex\n );\n\n (\n vars.nextLiquidityRate,\n vars.nextVariableRate\n ) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress)\n .calculateInterestRates(\n DataTypes.CalculateInterestRatesParams({\n liquidityAdded: liquidityAdded,\n liquidityTaken: liquidityTaken,\n totalVariableDebt: vars.totalVariableDebt,\n reserveFactor: reserveCache.reserveFactor,\n reserve: reserveAddress,\n xToken: reserveCache.xTokenAddress\n })\n );\n\n reserve.currentLiquidityRate = vars.nextLiquidityRate.toUint128();\n reserve.currentVariableBorrowRate = vars.nextVariableRate.toUint128();\n\n emit ReserveDataUpdated(\n reserveAddress,\n vars.nextLiquidityRate,\n vars.nextVariableRate,\n reserveCache.nextLiquidityIndex,\n reserveCache.nextVariableBorrowIndex\n );\n }\n\n struct AccrueToTreasuryLocalVars {\n uint256 prevTotalVariableDebt;\n uint256 currTotalVariableDebt;\n uint256 totalDebtAccrued;\n uint256 amountToMint;\n }\n\n /**\n * @notice Mints part of the repaid interest to the reserve treasury as a function of the reserve factor for the\n * specific asset.\n * @param reserve The reserve to be updated\n * @param reserveCache The caching layer for the reserve data\n **/\n function _accrueToTreasury(\n DataTypes.ReserveData storage reserve,\n DataTypes.ReserveCache memory reserveCache\n ) internal {\n AccrueToTreasuryLocalVars memory vars;\n\n if (reserveCache.reserveFactor == 0) {\n return;\n }\n\n //calculate the total variable debt at moment of the last interaction\n vars.prevTotalVariableDebt = reserveCache.currScaledVariableDebt.rayMul(\n reserveCache.currVariableBorrowIndex\n );\n\n //calculate the new total variable debt after accumulation of the interest on the index\n vars.currTotalVariableDebt = reserveCache.currScaledVariableDebt.rayMul(\n reserveCache.nextVariableBorrowIndex\n );\n\n //debt accrued is the sum of the current debt minus the sum of the debt at the last update\n vars.totalDebtAccrued =\n vars.currTotalVariableDebt -\n vars.prevTotalVariableDebt;\n\n vars.amountToMint = vars.totalDebtAccrued.percentMul(\n reserveCache.reserveFactor\n );\n\n if (vars.amountToMint != 0) {\n reserve.accruedToTreasury += vars\n .amountToMint\n .rayDiv(reserveCache.nextLiquidityIndex)\n .toUint128();\n }\n }\n\n /**\n * @notice Updates the reserve indexes and the timestamp of the update.\n * @param reserve The reserve reserve to be updated\n * @param reserveCache The cache layer holding the cached protocol data\n **/\n function _updateIndexes(\n DataTypes.ReserveData storage reserve,\n DataTypes.ReserveCache memory reserveCache\n ) internal {\n reserveCache.nextLiquidityIndex = reserveCache.currLiquidityIndex;\n reserveCache.nextVariableBorrowIndex = reserveCache\n .currVariableBorrowIndex;\n\n //only cumulating if there is any income being produced\n if (reserveCache.currLiquidityRate != 0) {\n uint256 cumulatedLiquidityInterest = MathUtils\n .calculateLinearInterest(\n reserveCache.currLiquidityRate,\n reserveCache.reserveLastUpdateTimestamp\n );\n reserveCache.nextLiquidityIndex = cumulatedLiquidityInterest.rayMul(\n reserveCache.currLiquidityIndex\n );\n reserve.liquidityIndex = reserveCache\n .nextLiquidityIndex\n .toUint128();\n\n //as the liquidity rate might come only from stable rate loans, we need to ensure\n //that there is actual variable debt before accumulating\n if (reserveCache.currScaledVariableDebt != 0) {\n uint256 cumulatedVariableBorrowInterest = MathUtils\n .calculateCompoundedInterest(\n reserveCache.currVariableBorrowRate,\n reserveCache.reserveLastUpdateTimestamp\n );\n reserveCache\n .nextVariableBorrowIndex = cumulatedVariableBorrowInterest\n .rayMul(reserveCache.currVariableBorrowIndex);\n reserve.variableBorrowIndex = reserveCache\n .nextVariableBorrowIndex\n .toUint128();\n }\n }\n\n //solium-disable-next-line\n reserve.lastUpdateTimestamp = uint40(block.timestamp);\n }\n\n /**\n * @notice Creates a cache object to avoid repeated storage reads and external contract calls when updating state and\n * interest rates.\n * @param reserve The reserve object for which the cache will be filled\n * @return The cache object\n */\n function cache(DataTypes.ReserveData storage reserve)\n internal\n view\n returns (DataTypes.ReserveCache memory)\n {\n DataTypes.ReserveCache memory reserveCache;\n\n reserveCache.reserveConfiguration = reserve.configuration;\n reserveCache.xTokenAddress = reserve.xTokenAddress;\n\n (, , , , DataTypes.AssetType reserveAssetType) = reserveCache\n .reserveConfiguration\n .getFlags();\n\n if (reserveAssetType == DataTypes.AssetType.ERC20) {\n reserveCache.reserveFactor = reserveCache\n .reserveConfiguration\n .getReserveFactor();\n reserveCache.currLiquidityIndex = reserve.liquidityIndex;\n reserveCache.currVariableBorrowIndex = reserve.variableBorrowIndex;\n reserveCache.currLiquidityRate = reserve.currentLiquidityRate;\n reserveCache.currVariableBorrowRate = reserve\n .currentVariableBorrowRate;\n\n reserveCache.variableDebtTokenAddress = reserve\n .variableDebtTokenAddress;\n\n reserveCache.reserveLastUpdateTimestamp = reserve\n .lastUpdateTimestamp;\n\n reserveCache.currScaledVariableDebt = reserveCache\n .nextScaledVariableDebt = IVariableDebtToken(\n reserveCache.variableDebtTokenAddress\n ).scaledTotalSupply();\n }\n\n return reserveCache;\n }\n}\n" }, "contracts/protocol/libraries/logic/MarketplaceLogic.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {IERC721} from \"../../../dependencies/openzeppelin/contracts/IERC721.sol\";\nimport {INToken} from \"../../../interfaces/INToken.sol\";\nimport {IPoolAddressesProvider} from \"../../../interfaces/IPoolAddressesProvider.sol\";\nimport {XTokenType} from \"../../../interfaces/IXTokenType.sol\";\nimport {ICollateralizableERC721} from \"../../../interfaces/ICollateralizableERC721.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {IPToken} from \"../../../interfaces/IPToken.sol\";\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {ValidationLogic} from \"./ValidationLogic.sol\";\nimport {SupplyLogic} from \"./SupplyLogic.sol\";\nimport {BorrowLogic} from \"./BorrowLogic.sol\";\nimport {SeaportInterface} from \"../../../dependencies/seaport/contracts/interfaces/SeaportInterface.sol\";\nimport {SafeERC20} from \"../../../dependencies/openzeppelin/contracts/SafeERC20.sol\";\nimport {IERC20} from \"../../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {IERC721} from \"../../../dependencies/openzeppelin/contracts/IERC721.sol\";\nimport {ConsiderationItem, OfferItem} from \"../../../dependencies/seaport/contracts/lib/ConsiderationStructs.sol\";\nimport {ItemType} from \"../../../dependencies/seaport/contracts/lib/ConsiderationEnums.sol\";\nimport {AdvancedOrder, CriteriaResolver, Fulfillment} from \"../../../dependencies/seaport/contracts/lib/ConsiderationStructs.sol\";\nimport {IWETH} from \"../../../misc/interfaces/IWETH.sol\";\nimport {UserConfiguration} from \"../configuration/UserConfiguration.sol\";\nimport {ReserveConfiguration} from \"../configuration/ReserveConfiguration.sol\";\nimport {IMarketplace} from \"../../../interfaces/IMarketplace.sol\";\nimport {Address} from \"../../../dependencies/openzeppelin/contracts/Address.sol\";\n\n/**\n * @title Marketplace library\n *\n * @notice Implements the base logic for all the actions related to NFT buy/accept bid\n */\nlibrary MarketplaceLogic {\n using UserConfiguration for DataTypes.UserConfigurationMap;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n using SafeERC20 for IERC20;\n\n event BuyWithCredit(\n bytes32 indexed marketplaceId,\n DataTypes.OrderInfo orderInfo,\n DataTypes.Credit credit\n );\n\n event AcceptBidWithCredit(\n bytes32 indexed marketplaceId,\n DataTypes.OrderInfo orderInfo,\n DataTypes.Credit credit\n );\n\n struct MarketplaceLocalVars {\n bool isETH;\n address xTokenAddress;\n address creditToken;\n uint256 creditAmount;\n address weth;\n uint256 ethLeft;\n bytes32 marketplaceId;\n bytes payload;\n DataTypes.Marketplace marketplace;\n DataTypes.OrderInfo orderInfo;\n }\n\n function executeBuyWithCredit(\n bytes32 marketplaceId,\n bytes calldata payload,\n DataTypes.Credit calldata credit,\n DataTypes.PoolStorage storage ps,\n IPoolAddressesProvider poolAddressProvider,\n uint16 referralCode\n ) external {\n MarketplaceLocalVars memory vars;\n\n vars.weth = poolAddressProvider.getWETH();\n DataTypes.Marketplace memory marketplace = poolAddressProvider\n .getMarketplace(marketplaceId);\n DataTypes.OrderInfo memory orderInfo = IMarketplace(marketplace.adapter)\n .getAskOrderInfo(payload, vars.weth);\n orderInfo.taker = msg.sender;\n vars.ethLeft = msg.value;\n\n _depositETH(vars, orderInfo);\n\n vars.ethLeft -= _buyWithCredit(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig[orderInfo.taker],\n DataTypes.ExecuteMarketplaceParams({\n marketplaceId: marketplaceId,\n payload: payload,\n credit: credit,\n ethLeft: vars.ethLeft,\n marketplace: marketplace,\n orderInfo: orderInfo,\n weth: vars.weth,\n referralCode: referralCode,\n reservesCount: ps._reservesCount,\n oracle: poolAddressProvider.getPriceOracle(),\n priceOracleSentinel: poolAddressProvider.getPriceOracleSentinel()\n })\n );\n\n _refundETH(vars.ethLeft);\n }\n\n /**\n * @notice Implements the buyWithCredit feature. BuyWithCredit allows users to buy NFT from various NFT marketplaces\n * including OpenSea, LooksRare, X2Y2 etc. Users can use NFT's credit and will need to pay at most (1 - LTV) * $NFT\n * @dev Emits the `BuyWithCredit()` event\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n * @param params The additional parameters needed to execute the buyWithCredit function\n */\n function _buyWithCredit(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteMarketplaceParams memory params\n ) internal returns (uint256) {\n ValidationLogic.validateBuyWithCredit(params);\n\n MarketplaceLocalVars memory vars = _cache(params);\n\n _borrowTo(reservesData, params, vars, address(this));\n\n (uint256 priceEth, uint256 downpaymentEth) = _delegateToPool(\n params,\n vars\n );\n\n // delegateCall to avoid extra token transfer\n Address.functionDelegateCall(\n params.marketplace.adapter,\n abi.encodeWithSelector(\n IMarketplace.matchAskWithTakerBid.selector,\n params.marketplace.marketplace,\n params.payload,\n priceEth\n )\n );\n\n _repay(\n reservesData,\n reservesList,\n userConfig,\n params,\n vars,\n params.orderInfo.taker\n );\n\n emit BuyWithCredit(\n params.marketplaceId,\n params.orderInfo,\n params.credit\n );\n\n return downpaymentEth;\n }\n\n function executeBatchBuyWithCredit(\n bytes32[] calldata marketplaceIds,\n bytes[] calldata payloads,\n DataTypes.Credit[] calldata credits,\n DataTypes.PoolStorage storage ps,\n IPoolAddressesProvider poolAddressProvider,\n uint16 referralCode\n ) external {\n MarketplaceLocalVars memory vars;\n\n vars.weth = poolAddressProvider.getWETH();\n require(\n marketplaceIds.length == payloads.length &&\n payloads.length == credits.length,\n Errors.INCONSISTENT_PARAMS_LENGTH\n );\n vars.ethLeft = msg.value;\n for (uint256 i = 0; i < marketplaceIds.length; i++) {\n vars.marketplaceId = marketplaceIds[i];\n vars.payload = payloads[i];\n DataTypes.Credit memory credit = credits[i];\n\n DataTypes.Marketplace memory marketplace = poolAddressProvider\n .getMarketplace(vars.marketplaceId);\n DataTypes.OrderInfo memory orderInfo = IMarketplace(\n marketplace.adapter\n ).getAskOrderInfo(vars.payload, vars.weth);\n orderInfo.taker = msg.sender;\n\n // Once we encounter a listing using WETH, then we convert all our ethLeft to WETH\n // this also means that the parameters order is very important\n //\n // frontend/sdk needs to guarantee that WETH orders will always be put after ALL\n // ETH orders, all ETH orders after WETH orders will fail\n //\n // eg. The following example image that the `taker` owns only ETH and wants to\n // batch buy bunch of NFTs which are listed using WETH and ETH\n //\n // batchBuyWithCredit([ETH, WETH, ETH]) => ko\n // | -> convert all ethLeft to WETH, 3rd purchase will fail\n // batchBuyWithCredit([ETH, ETH, ETH]) => ok\n // batchBuyWithCredit([ETH, ETH, WETH]) => ok\n //\n _depositETH(vars, orderInfo);\n\n vars.ethLeft -= _buyWithCredit(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig[orderInfo.taker],\n DataTypes.ExecuteMarketplaceParams({\n marketplaceId: vars.marketplaceId,\n payload: vars.payload,\n credit: credit,\n ethLeft: vars.ethLeft,\n marketplace: marketplace,\n orderInfo: orderInfo,\n weth: vars.weth,\n referralCode: referralCode,\n reservesCount: ps._reservesCount,\n oracle: poolAddressProvider.getPriceOracle(),\n priceOracleSentinel: poolAddressProvider\n .getPriceOracleSentinel()\n })\n );\n }\n\n _refundETH(vars.ethLeft);\n }\n\n function executeAcceptBidWithCredit(\n bytes32 marketplaceId,\n bytes calldata payload,\n DataTypes.Credit calldata credit,\n address onBehalfOf,\n DataTypes.PoolStorage storage ps,\n IPoolAddressesProvider poolAddressProvider,\n uint16 referralCode\n ) external {\n MarketplaceLocalVars memory vars;\n\n vars.weth = poolAddressProvider.getWETH();\n vars.marketplace = poolAddressProvider.getMarketplace(marketplaceId);\n vars.orderInfo = IMarketplace(vars.marketplace.adapter).getBidOrderInfo(\n payload\n );\n require(vars.orderInfo.taker == onBehalfOf, Errors.INVALID_ORDER_TAKER);\n\n _acceptBidWithCredit(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig[vars.orderInfo.maker],\n DataTypes.ExecuteMarketplaceParams({\n marketplaceId: marketplaceId,\n payload: payload,\n credit: credit,\n ethLeft: 0,\n marketplace: vars.marketplace,\n orderInfo: vars.orderInfo,\n weth: vars.weth,\n referralCode: referralCode,\n reservesCount: ps._reservesCount,\n oracle: poolAddressProvider.getPriceOracle(),\n priceOracleSentinel: poolAddressProvider.getPriceOracleSentinel()\n })\n );\n }\n\n function executeBatchAcceptBidWithCredit(\n bytes32[] calldata marketplaceIds,\n bytes[] calldata payloads,\n DataTypes.Credit[] calldata credits,\n address onBehalfOf,\n DataTypes.PoolStorage storage ps,\n IPoolAddressesProvider poolAddressProvider,\n uint16 referralCode\n ) external {\n MarketplaceLocalVars memory vars;\n\n vars.weth = poolAddressProvider.getWETH();\n require(\n marketplaceIds.length == payloads.length &&\n payloads.length == credits.length,\n Errors.INCONSISTENT_PARAMS_LENGTH\n );\n for (uint256 i = 0; i < marketplaceIds.length; i++) {\n vars.marketplaceId = marketplaceIds[i];\n vars.payload = payloads[i];\n DataTypes.Credit memory credit = credits[i];\n\n vars.marketplace = poolAddressProvider.getMarketplace(\n vars.marketplaceId\n );\n vars.orderInfo = IMarketplace(vars.marketplace.adapter)\n .getBidOrderInfo(vars.payload);\n require(\n vars.orderInfo.taker == onBehalfOf,\n Errors.INVALID_ORDER_TAKER\n );\n\n _acceptBidWithCredit(\n ps._reserves,\n ps._reservesList,\n ps._usersConfig[vars.orderInfo.maker],\n DataTypes.ExecuteMarketplaceParams({\n marketplaceId: vars.marketplaceId,\n payload: vars.payload,\n credit: credit,\n ethLeft: 0,\n marketplace: vars.marketplace,\n orderInfo: vars.orderInfo,\n weth: vars.weth,\n referralCode: referralCode,\n reservesCount: ps._reservesCount,\n oracle: poolAddressProvider.getPriceOracle(),\n priceOracleSentinel: poolAddressProvider\n .getPriceOracleSentinel()\n })\n );\n }\n }\n\n /**\n * @notice Implements the acceptBidWithCredit feature. AcceptBidWithCredit allows users to\n * accept a leveraged bid on ParaSpace NFT marketplace. Users can submit leveraged bid and pay\n * at most (1 - LTV) * $NFT\n * @dev Emits the `AcceptBidWithCredit()` event\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n * @param params The additional parameters needed to execute the acceptBidWithCredit function\n */\n function _acceptBidWithCredit(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteMarketplaceParams memory params\n ) internal {\n ValidationLogic.validateAcceptBidWithCredit(params);\n\n MarketplaceLocalVars memory vars = _cache(params);\n\n _borrowTo(reservesData, params, vars, params.orderInfo.maker);\n\n // delegateCall to avoid extra token transfer\n Address.functionDelegateCall(\n params.marketplace.adapter,\n abi.encodeWithSelector(\n IMarketplace.matchBidWithTakerAsk.selector,\n params.marketplace.marketplace,\n params.payload\n )\n );\n\n _repay(\n reservesData,\n reservesList,\n userConfig,\n params,\n vars,\n params.orderInfo.maker\n );\n\n emit AcceptBidWithCredit(\n params.marketplaceId,\n params.orderInfo,\n params.credit\n );\n }\n\n /**\n * @notice Transfer payNow portion from taker to this contract. This is only useful\n * in buyWithCredit.\n * @dev\n * @param params The additional parameters needed to execute the buyWithCredit/acceptBidWithCredit function\n * @param vars The marketplace local vars for caching storage values for future reads\n */\n function _delegateToPool(\n DataTypes.ExecuteMarketplaceParams memory params,\n MarketplaceLocalVars memory vars\n ) internal returns (uint256, uint256) {\n uint256 price = 0;\n\n for (uint256 i = 0; i < params.orderInfo.consideration.length; i++) {\n ConsiderationItem memory item = params.orderInfo.consideration[i];\n require(\n item.startAmount == item.endAmount,\n Errors.INVALID_MARKETPLACE_ORDER\n );\n require(\n item.itemType == ItemType.ERC20 ||\n (vars.isETH && item.itemType == ItemType.NATIVE),\n Errors.INVALID_ASSET_TYPE\n );\n require(\n item.token == params.credit.token,\n Errors.CREDIT_DOES_NOT_MATCH_ORDER\n );\n price += item.startAmount;\n }\n\n uint256 downpayment = price - vars.creditAmount;\n if (!vars.isETH) {\n IERC20(vars.creditToken).safeTransferFrom(\n params.orderInfo.taker,\n address(this),\n downpayment\n );\n _checkAllowance(vars.creditToken, params.marketplace.operator);\n // convert to (priceEth, downpaymentEth)\n price = 0;\n downpayment = 0;\n } else {\n require(params.ethLeft >= downpayment, Errors.PAYNOW_NOT_ENOUGH);\n }\n\n return (price, downpayment);\n }\n\n /**\n * @notice Borrow credit.amount from `credit.token` reserve without collateral. The corresponding\n * debt will be minted in the same block to the borrower.\n * @dev\n * @param reservesData The state of all the reserves\n * @param params The additional parameters needed to execute the buyWithCredit/acceptBidWithCredit function\n * @param vars The marketplace local vars for caching storage values for future reads\n * @param to The receiver of borrowed tokens\n */\n function _borrowTo(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.ExecuteMarketplaceParams memory params,\n MarketplaceLocalVars memory vars,\n address to\n ) internal {\n if (vars.creditAmount == 0) {\n return;\n }\n\n DataTypes.ReserveData storage reserve = reservesData[vars.creditToken];\n vars.xTokenAddress = reserve.xTokenAddress;\n\n require(vars.xTokenAddress != address(0), Errors.ASSET_NOT_LISTED);\n ValidationLogic.validateFlashloanSimple(reserve);\n // TODO: support PToken\n IPToken(vars.xTokenAddress).transferUnderlyingTo(to, vars.creditAmount);\n\n if (vars.isETH) {\n // No re-entrancy because it sent to our contract address\n IWETH(params.weth).withdraw(vars.creditAmount);\n }\n }\n\n /**\n * @notice Repay credit.amount by minting debt to the borrower. Borrower's received NFT\n * will also need to be supplied to the pool to provide bigger borrow limit.\n * @dev\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n * @param params The additional parameters needed to execute the buyWithCredit/acceptBidWithCredit function\n * @param vars The marketplace local vars for caching storage values for future reads\n * @param onBehalfOf The receiver of minted debt and NToken\n */\n function _repay(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteMarketplaceParams memory params,\n MarketplaceLocalVars memory vars,\n address onBehalfOf\n ) internal {\n for (uint256 i = 0; i < params.orderInfo.offer.length; i++) {\n OfferItem memory item = params.orderInfo.offer[i];\n require(\n item.itemType == ItemType.ERC721,\n Errors.INVALID_ASSET_TYPE\n );\n\n // underlyingAsset\n address token = item.token;\n uint256 tokenId = item.identifierOrCriteria;\n // NToken\n vars.xTokenAddress = reservesData[token].xTokenAddress;\n\n // item.token == NToken\n if (vars.xTokenAddress == address(0)) {\n address underlyingAsset = INToken(token)\n .UNDERLYING_ASSET_ADDRESS();\n bool isNToken = reservesData[underlyingAsset].xTokenAddress ==\n token;\n require(isNToken, Errors.ASSET_NOT_LISTED);\n vars.xTokenAddress = token;\n token = underlyingAsset;\n }\n\n require(\n INToken(vars.xTokenAddress).getXTokenType() !=\n XTokenType.NTokenUniswapV3,\n Errors.UNIV3_NOT_ALLOWED\n );\n\n // item.token == underlyingAsset but supplied after listing/offering\n // so NToken is transferred instead\n if (INToken(vars.xTokenAddress).ownerOf(tokenId) == address(this)) {\n _transferAndCollateralize(\n reservesData,\n userConfig,\n vars,\n token,\n tokenId,\n onBehalfOf\n );\n // item.token == underlyingAsset and underlyingAsset stays in wallet\n } else {\n DataTypes.ERC721SupplyParams[]\n memory tokenData = new DataTypes.ERC721SupplyParams[](1);\n tokenData[0] = DataTypes.ERC721SupplyParams(tokenId, true);\n SupplyLogic.executeSupplyERC721(\n reservesData,\n userConfig,\n DataTypes.ExecuteSupplyERC721Params({\n asset: token,\n tokenData: tokenData,\n onBehalfOf: onBehalfOf,\n payer: address(this),\n referralCode: params.referralCode\n })\n );\n }\n }\n\n if (vars.creditAmount == 0) {\n return;\n }\n\n BorrowLogic.executeBorrow(\n reservesData,\n reservesList,\n userConfig,\n DataTypes.ExecuteBorrowParams({\n asset: vars.creditToken,\n user: onBehalfOf,\n onBehalfOf: onBehalfOf,\n amount: vars.creditAmount,\n referralCode: params.referralCode,\n releaseUnderlying: false,\n reservesCount: params.reservesCount,\n oracle: params.oracle,\n priceOracleSentinel: params.priceOracleSentinel\n })\n );\n }\n\n function _checkAllowance(address token, address operator) internal {\n uint256 allowance = IERC20(token).allowance(address(this), operator);\n if (allowance == 0) {\n IERC20(token).safeApprove(operator, type(uint256).max);\n }\n }\n\n function _cache(DataTypes.ExecuteMarketplaceParams memory params)\n internal\n pure\n returns (MarketplaceLocalVars memory vars)\n {\n vars.isETH = params.credit.token == address(0);\n vars.creditToken = vars.isETH ? params.weth : params.credit.token;\n vars.creditAmount = params.credit.amount;\n }\n\n function _refundETH(uint256 ethLeft) internal {\n if (ethLeft > 0) {\n Address.sendValue(payable(msg.sender), ethLeft);\n }\n }\n\n function _depositETH(\n MarketplaceLocalVars memory vars,\n DataTypes.OrderInfo memory orderInfo\n ) internal {\n if (\n vars.ethLeft > 0 &&\n orderInfo.consideration[0].itemType != ItemType.NATIVE\n ) {\n IWETH(vars.weth).deposit{value: vars.ethLeft}();\n IERC20(vars.weth).safeTransferFrom(\n address(this),\n msg.sender,\n vars.ethLeft\n );\n vars.ethLeft = 0;\n }\n }\n\n function _transferAndCollateralize(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.UserConfigurationMap storage userConfig,\n MarketplaceLocalVars memory vars,\n address token,\n uint256 tokenId,\n address onBehalfOf\n ) internal {\n uint256[] memory tokenIds = new uint256[](1);\n tokenIds[0] = tokenId;\n\n IERC721(vars.xTokenAddress).safeTransferFrom(\n address(this),\n onBehalfOf,\n tokenId\n );\n SupplyLogic.executeCollateralizeERC721(\n reservesData,\n userConfig,\n token,\n tokenIds,\n onBehalfOf\n );\n }\n}\n" }, "contracts/protocol/libraries/logic/BorrowLogic.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {GPv2SafeERC20} from \"../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol\";\nimport {SafeCast} from \"../../../dependencies/openzeppelin/contracts/SafeCast.sol\";\nimport {IERC20} from \"../../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {IVariableDebtToken} from \"../../../interfaces/IVariableDebtToken.sol\";\nimport {IPToken} from \"../../../interfaces/IPToken.sol\";\nimport {UserConfiguration} from \"../configuration/UserConfiguration.sol\";\nimport {ReserveConfiguration} from \"../configuration/ReserveConfiguration.sol\";\nimport {Helpers} from \"../helpers/Helpers.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {ValidationLogic} from \"./ValidationLogic.sol\";\nimport {ReserveLogic} from \"./ReserveLogic.sol\";\n\n/**\n * @title BorrowLogic library\n *\n * @notice Implements the base logic for all the actions related to borrowing\n */\nlibrary BorrowLogic {\n using ReserveLogic for DataTypes.ReserveData;\n using GPv2SafeERC20 for IERC20;\n using UserConfiguration for DataTypes.UserConfigurationMap;\n\n // See `IPool` for descriptions\n event Borrow(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint256 borrowRate,\n uint16 indexed referralCode\n );\n event Repay(\n address indexed reserve,\n address indexed user,\n address indexed repayer,\n uint256 amount,\n bool usePTokens\n );\n\n /**\n * @notice Implements the borrow feature. Borrowing allows users that provided collateral to draw liquidity from the\n * ParaSpace protocol proportionally to their collateralization power.\n * @dev Emits the `Borrow()` event\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n * @param params The additional parameters needed to execute the borrow function\n */\n function executeBorrow(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteBorrowParams memory params\n ) public {\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n reserve.updateState(reserveCache);\n\n ValidationLogic.validateBorrow(\n reservesData,\n reservesList,\n DataTypes.ValidateBorrowParams({\n reserveCache: reserveCache,\n userConfig: userConfig,\n asset: params.asset,\n userAddress: params.onBehalfOf,\n amount: params.amount,\n reservesCount: params.reservesCount,\n oracle: params.oracle,\n priceOracleSentinel: params.priceOracleSentinel\n })\n );\n\n bool isFirstBorrowing = false;\n\n (\n isFirstBorrowing,\n reserveCache.nextScaledVariableDebt\n ) = IVariableDebtToken(reserveCache.variableDebtTokenAddress).mint(\n params.user,\n params.onBehalfOf,\n params.amount,\n reserveCache.nextVariableBorrowIndex\n );\n\n if (isFirstBorrowing) {\n userConfig.setBorrowing(reserve.id, true);\n }\n\n reserve.updateInterestRates(\n reserveCache,\n params.asset,\n 0,\n params.releaseUnderlying ? params.amount : 0\n );\n\n if (params.releaseUnderlying) {\n IPToken(reserveCache.xTokenAddress).transferUnderlyingTo(\n params.user,\n params.amount\n );\n }\n\n emit Borrow(\n params.asset,\n params.user,\n params.onBehalfOf,\n params.amount,\n reserve.currentVariableBorrowRate,\n params.referralCode\n );\n }\n\n /**\n * @notice Implements the repay feature. Repaying transfers the underlying back to the xToken and clears the\n * equivalent amount of debt for the user by burning the corresponding debt token.\n * @dev Emits the `Repay()` event\n * @param reservesData The state of all the reserves\n * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n * @param params The additional parameters needed to execute the repay function\n * @return The actual amount being repaid\n */\n function executeRepay(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteRepayParams memory params\n ) external returns (uint256) {\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n reserve.updateState(reserveCache);\n\n uint256 variableDebt = Helpers.getUserCurrentDebt(\n params.onBehalfOf,\n reserveCache.variableDebtTokenAddress\n );\n\n ValidationLogic.validateRepay(\n reserveCache,\n params.amount,\n params.onBehalfOf,\n variableDebt\n );\n\n uint256 paybackAmount = variableDebt;\n\n // Allows a user to repay with xTokens without leaving dust from interest.\n if (params.usePTokens && params.amount == type(uint256).max) {\n params.amount = IPToken(reserveCache.xTokenAddress).balanceOf(\n msg.sender\n );\n }\n\n // if amount user is sending is less than payback amount (debt), update the payback amount to what the user is sending\n if (params.amount < paybackAmount) {\n paybackAmount = params.amount;\n }\n\n reserveCache.nextScaledVariableDebt = IVariableDebtToken(\n reserveCache.variableDebtTokenAddress\n ).burn(\n params.onBehalfOf,\n paybackAmount,\n reserveCache.nextVariableBorrowIndex\n );\n\n reserve.updateInterestRates(\n reserveCache,\n params.asset,\n params.usePTokens ? 0 : paybackAmount,\n 0\n );\n\n if (variableDebt - paybackAmount == 0) {\n userConfig.setBorrowing(reserve.id, false);\n }\n\n if (params.usePTokens) {\n IPToken(reserveCache.xTokenAddress).burn(\n msg.sender,\n reserveCache.xTokenAddress,\n paybackAmount,\n reserveCache.nextLiquidityIndex\n );\n } else {\n // send paybackAmount from user to reserve\n IERC20(params.asset).safeTransferFrom(\n msg.sender,\n reserveCache.xTokenAddress,\n paybackAmount\n );\n IPToken(reserveCache.xTokenAddress).handleRepayment(\n msg.sender,\n paybackAmount\n );\n }\n\n emit Repay(\n params.asset,\n params.onBehalfOf,\n msg.sender,\n paybackAmount,\n params.usePTokens\n );\n\n return paybackAmount;\n }\n}\n" }, "contracts/protocol/libraries/logic/LiquidationLogic.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {IERC20} from \"../../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {GPv2SafeERC20} from \"../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol\";\nimport {PercentageMath} from \"../../libraries/math/PercentageMath.sol\";\nimport {WadRayMath} from \"../../libraries/math/WadRayMath.sol\";\nimport {Math} from \"../../../dependencies/openzeppelin/contracts/Math.sol\";\nimport {Helpers} from \"../../libraries/helpers/Helpers.sol\";\nimport {DataTypes} from \"../../libraries/types/DataTypes.sol\";\nimport {ReserveLogic} from \"./ReserveLogic.sol\";\nimport {SupplyLogic} from \"./SupplyLogic.sol\";\nimport {ValidationLogic} from \"./ValidationLogic.sol\";\nimport {GenericLogic} from \"./GenericLogic.sol\";\nimport {UserConfiguration} from \"../../libraries/configuration/UserConfiguration.sol\";\nimport {ReserveConfiguration} from \"../../libraries/configuration/ReserveConfiguration.sol\";\nimport {Address} from \"../../../dependencies/openzeppelin/contracts/Address.sol\";\nimport {IPToken} from \"../../../interfaces/IPToken.sol\";\nimport {IWETH} from \"../../../misc/interfaces/IWETH.sol\";\nimport {ICollateralizableERC721} from \"../../../interfaces/ICollateralizableERC721.sol\";\nimport {IAuctionableERC721} from \"../../../interfaces/IAuctionableERC721.sol\";\nimport {INToken} from \"../../../interfaces/INToken.sol\";\nimport {PRBMath} from \"../../../dependencies/math/PRBMath.sol\";\nimport {PRBMathUD60x18} from \"../../../dependencies/math/PRBMathUD60x18.sol\";\nimport {IReserveAuctionStrategy} from \"../../../interfaces/IReserveAuctionStrategy.sol\";\nimport {IVariableDebtToken} from \"../../../interfaces/IVariableDebtToken.sol\";\nimport {IPriceOracleGetter} from \"../../../interfaces/IPriceOracleGetter.sol\";\nimport {IPoolAddressesProvider} from \"../../../interfaces/IPoolAddressesProvider.sol\";\nimport {Errors} from \"../../libraries/helpers/Errors.sol\";\n\n/**\n * @title LiquidationLogic library\n *\n * @notice Implements actions involving management of collateral in the protocol, the main one being the liquidations\n **/\nlibrary LiquidationLogic {\n using PercentageMath for uint256;\n using ReserveLogic for DataTypes.ReserveCache;\n using ReserveLogic for DataTypes.ReserveData;\n using UserConfiguration for DataTypes.UserConfigurationMap;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n using PRBMathUD60x18 for uint256;\n using GPv2SafeERC20 for IERC20;\n\n /**\n * @dev Default percentage of borrower's debt to be repaid in a liquidation.\n * @dev Percentage applied when the users health factor is above `CLOSE_FACTOR_HF_THRESHOLD`\n * Expressed in bps, a value of 0.5e4 results in 50.00%\n */\n uint256 internal constant DEFAULT_LIQUIDATION_CLOSE_FACTOR = 0.5e4;\n\n /**\n * @dev Maximum percentage of borrower's debt to be repaid in a liquidation\n * @dev Percentage applied when the users health factor is below `CLOSE_FACTOR_HF_THRESHOLD`\n * Expressed in bps, a value of 1e4 results in 100.00%\n */\n uint256 public constant MAX_LIQUIDATION_CLOSE_FACTOR = 1e4;\n\n /**\n * @dev This constant represents below which health factor value it is possible to liquidate\n * an amount of debt corresponding to `MAX_LIQUIDATION_CLOSE_FACTOR`.\n * A value of 0.95e18 results in 95%\n */\n uint256 public constant CLOSE_FACTOR_HF_THRESHOLD = 0.95e18;\n\n // See `IPool` for descriptions\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n event LiquidateERC20(\n address indexed collateralAsset,\n address indexed liquidationAsset,\n address indexed borrower,\n uint256 liquidationAmount,\n uint256 liquidatedCollateralAmount,\n address liquidator,\n bool receivePToken\n );\n event LiquidateERC721(\n address indexed collateralAsset,\n address indexed liquidationAsset,\n address indexed borrower,\n uint256 liquidationAmount,\n uint256 liquidatedCollateralTokenId,\n address liquidator,\n bool receiveNToken\n );\n event AuctionEnded(\n address indexed user,\n address indexed collateralAsset,\n uint256 indexed collateralTokenId\n );\n\n struct ExecuteLiquidateLocalVars {\n //userCollateral from collateralReserve\n uint256 userCollateral;\n //userGlobalCollateral from all reserves\n uint256 userGlobalCollateral;\n //userDebt from liquadationReserve\n uint256 userDebt;\n //userGlobalDebt from all reserves\n uint256 userGlobalDebt;\n //actualLiquidationAmount to repay based on collateral\n uint256 actualLiquidationAmount;\n //actualCollateral allowed to liquidate\n uint256 actualCollateralToLiquidate;\n //liquidationBonusRate from reserve config\n uint256 liquidationBonus;\n //user health factor\n uint256 healthFactor;\n //liquidation protocol fee to be sent to treasury\n uint256 liquidationProtocolFee;\n //liquidation funds payer\n address payer;\n //collateral P|N Token\n address collateralXToken;\n //auction strategy\n address auctionStrategyAddress;\n //liquidation asset reserve id\n uint16 liquidationAssetReserveId;\n //whether auction is enabled\n bool auctionEnabled;\n //liquidation reserve cache\n DataTypes.ReserveCache liquidationAssetReserveCache;\n }\n\n struct LiquidateParametersLocalVars {\n uint256 userCollateral;\n uint256 collateralPrice;\n uint256 liquidationAssetPrice;\n uint256 liquidationAssetDecimals;\n uint256 collateralDecimals;\n uint256 collateralAssetUnit;\n uint256 liquidationAssetUnit;\n uint256 actualCollateralToLiquidate;\n uint256 actualLiquidationAmount;\n uint256 actualLiquidationBonus;\n uint256 liquidationProtocolFeePercentage;\n uint256 liquidationProtocolFee;\n // Auction related\n uint256 auctionMultiplier;\n uint256 auctionStartTime;\n }\n\n /**\n * @notice Function to liquidate a position if its Health Factor drops below 1. The caller (liquidator)\n * covers `liquidationAmount` amount of debt of the user getting liquidated, and receives\n * a proportional amount of the `collateralAsset` plus a bonus to cover market risk\n * @dev Emits the `LiquidateERC20()` event\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n * @param params The additional parameters needed to execute the liquidation function\n * @return actualLiquidationAmount The actual debt that is getting liquidated.\n **/\n function executeLiquidateERC20(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n DataTypes.ExecuteLiquidateParams memory params\n ) external returns (uint256) {\n ExecuteLiquidateLocalVars memory vars;\n\n DataTypes.ReserveData storage collateralReserve = reservesData[\n params.collateralAsset\n ];\n DataTypes.ReserveData storage liquidationAssetReserve = reservesData[\n params.liquidationAsset\n ];\n DataTypes.UserConfigurationMap storage userConfig = usersConfig[\n params.borrower\n ];\n vars.liquidationAssetReserveCache = liquidationAssetReserve.cache();\n liquidationAssetReserve.updateState(vars.liquidationAssetReserveCache);\n\n (, , , , , , , vars.healthFactor, , ) = GenericLogic\n .calculateUserAccountData(\n reservesData,\n reservesList,\n DataTypes.CalculateUserAccountDataParams({\n userConfig: userConfig,\n reservesCount: params.reservesCount,\n user: params.borrower,\n oracle: params.priceOracle\n })\n );\n\n (vars.userDebt, vars.actualLiquidationAmount) = _calculateDebt(\n params,\n vars\n );\n\n (vars.collateralXToken, vars.liquidationBonus) = _getConfigurationData(\n collateralReserve\n );\n\n (\n vars.userCollateral,\n vars.actualCollateralToLiquidate,\n vars.actualLiquidationAmount,\n vars.liquidationProtocolFee\n ) = _calculateERC20LiquidationParameters(\n collateralReserve,\n params,\n vars\n );\n\n ValidationLogic.validateLiquidateERC20(\n userConfig,\n collateralReserve,\n DataTypes.ValidateLiquidateERC20Params({\n liquidationAssetReserveCache: vars.liquidationAssetReserveCache,\n weth: params.weth,\n liquidationAmount: params.liquidationAmount,\n actualLiquidationAmount: vars.actualLiquidationAmount,\n liquidationAsset: params.liquidationAsset,\n totalDebt: vars.userDebt,\n healthFactor: vars.healthFactor,\n priceOracleSentinel: params.priceOracleSentinel\n })\n );\n\n if (vars.userDebt == vars.actualLiquidationAmount) {\n userConfig.setBorrowing(liquidationAssetReserve.id, false);\n }\n\n // If the collateral being liquidated is equal to the user balance,\n // we set the currency as not being used as collateral anymore\n if (\n vars.actualCollateralToLiquidate + vars.liquidationProtocolFee ==\n vars.userCollateral\n ) {\n userConfig.setUsingAsCollateral(collateralReserve.id, false);\n emit ReserveUsedAsCollateralDisabled(\n params.collateralAsset,\n params.borrower\n );\n }\n\n // Transfer fee to treasury if it is non-zero\n if (vars.liquidationProtocolFee != 0) {\n IPToken(vars.collateralXToken).transferOnLiquidation(\n params.borrower,\n IPToken(vars.collateralXToken).RESERVE_TREASURY_ADDRESS(),\n vars.liquidationProtocolFee\n );\n }\n\n _burnDebtTokens(liquidationAssetReserve, params, vars);\n\n if (params.receiveXToken) {\n _liquidatePTokens(usersConfig, collateralReserve, params, vars);\n } else {\n _burnCollateralPTokens(collateralReserve, params, vars);\n }\n\n emit LiquidateERC20(\n params.collateralAsset,\n params.liquidationAsset,\n params.borrower,\n vars.actualLiquidationAmount,\n vars.actualCollateralToLiquidate,\n params.liquidator,\n params.receiveXToken\n );\n\n return vars.actualLiquidationAmount;\n }\n\n /**\n * @notice Function to liquidate an ERC721 of a position if its Health Factor drops below 1. The caller (liquidator)\n * covers `liquidationAmount` amount of debt of the user getting liquidated, and receives\n * a proportional tokenId of the `collateralAsset` minus a bonus to cover market risk\n * @dev Emits the `LiquidateERC721()` event\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n * @param params The additional parameters needed to execute the liquidation function\n * @return actualLiquidationAmount The actual liquidation amount.\n **/\n function executeLiquidateERC721(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n DataTypes.ExecuteLiquidateParams memory params\n ) external returns (uint256) {\n ExecuteLiquidateLocalVars memory vars;\n\n DataTypes.ReserveData storage collateralReserve = reservesData[\n params.collateralAsset\n ];\n DataTypes.ReserveData storage liquidationAssetReserve = reservesData[\n params.liquidationAsset\n ];\n DataTypes.UserConfigurationMap storage userConfig = usersConfig[\n params.borrower\n ];\n\n vars.liquidationAssetReserveId = liquidationAssetReserve.id;\n vars.liquidationAssetReserveCache = liquidationAssetReserve.cache();\n // liquidationAssetReserve.updateState(vars.liquidationAssetReserveCache);\n\n vars.auctionStrategyAddress = collateralReserve.auctionStrategyAddress;\n vars.auctionEnabled = vars.auctionStrategyAddress != address(0);\n\n (\n vars.userGlobalCollateral,\n ,\n vars.userGlobalDebt, //in base currency\n ,\n ,\n ,\n ,\n ,\n vars.healthFactor,\n\n ) = GenericLogic.calculateUserAccountData(\n reservesData,\n reservesList,\n DataTypes.CalculateUserAccountDataParams({\n userConfig: userConfig,\n reservesCount: params.reservesCount,\n user: params.borrower,\n oracle: params.priceOracle\n })\n );\n\n (vars.collateralXToken, vars.liquidationBonus) = _getConfigurationData(\n collateralReserve\n );\n if (vars.auctionEnabled) {\n vars.liquidationBonus = PercentageMath.PERCENTAGE_FACTOR;\n }\n\n (\n vars.userCollateral,\n vars.actualLiquidationAmount,\n vars.liquidationProtocolFee,\n vars.userGlobalDebt\n ) = _calculateERC721LiquidationParameters(\n collateralReserve,\n params,\n vars\n );\n\n ValidationLogic.validateLiquidateERC721(\n reservesData,\n userConfig,\n collateralReserve,\n DataTypes.ValidateLiquidateERC721Params({\n liquidationAssetReserveCache: vars.liquidationAssetReserveCache,\n liquidator: params.liquidator,\n borrower: params.borrower,\n globalDebt: vars.userGlobalDebt,\n actualLiquidationAmount: vars.actualLiquidationAmount,\n maxLiquidationAmount: params.liquidationAmount,\n healthFactor: vars.healthFactor,\n priceOracleSentinel: params.priceOracleSentinel,\n collateralAsset: params.collateralAsset,\n tokenId: params.collateralTokenId,\n xTokenAddress: vars.collateralXToken,\n auctionEnabled: vars.auctionEnabled,\n auctionRecoveryHealthFactor: params.auctionRecoveryHealthFactor\n })\n );\n\n if (vars.auctionEnabled) {\n IAuctionableERC721(vars.collateralXToken).endAuction(\n params.collateralTokenId\n );\n emit AuctionEnded(\n params.borrower,\n params.collateralAsset,\n params.collateralTokenId\n );\n }\n\n _supplyNewCollateral(reservesData, userConfig, params, vars);\n\n // If the collateral being liquidated is equal to the user balance,\n // we set the currency as not being used as collateral anymore\n if (vars.userCollateral == 1) {\n userConfig.setUsingAsCollateral(collateralReserve.id, false);\n emit ReserveUsedAsCollateralDisabled(\n params.collateralAsset,\n params.borrower\n );\n }\n\n // Transfer fee to treasury if it is non-zero\n if (vars.liquidationProtocolFee != 0) {\n IERC20(params.liquidationAsset).safeTransferFrom(\n vars.payer,\n IPToken(vars.liquidationAssetReserveCache.xTokenAddress)\n .RESERVE_TREASURY_ADDRESS(),\n vars.liquidationProtocolFee\n );\n }\n\n if (params.receiveXToken) {\n INToken(vars.collateralXToken).transferOnLiquidation(\n params.borrower,\n params.liquidator,\n params.collateralTokenId\n );\n } else {\n _burnCollateralNTokens(params, vars);\n }\n\n emit LiquidateERC721(\n params.collateralAsset,\n params.liquidationAsset,\n params.borrower,\n vars.actualLiquidationAmount,\n params.collateralTokenId,\n params.liquidator,\n params.receiveXToken\n );\n\n return vars.actualLiquidationAmount;\n }\n\n /**\n * @notice Burns the collateral xTokens and transfers the underlying to the liquidator.\n * @dev The function also updates the state and the interest rate of the collateral reserve.\n * @param collateralReserve The data of the collateral reserve\n * @param params The additional parameters needed to execute the liquidation function\n * @param vars The executeLiquidateERC20() function local vars\n */\n function _burnCollateralPTokens(\n DataTypes.ReserveData storage collateralReserve,\n DataTypes.ExecuteLiquidateParams memory params,\n ExecuteLiquidateLocalVars memory vars\n ) internal {\n DataTypes.ReserveCache memory collateralReserveCache = collateralReserve\n .cache();\n collateralReserve.updateState(collateralReserveCache);\n collateralReserve.updateInterestRates(\n collateralReserveCache,\n params.collateralAsset,\n 0,\n vars.actualCollateralToLiquidate\n );\n\n // Burn the equivalent amount of xToken, sending the underlying to the liquidator\n IPToken(vars.collateralXToken).burn(\n params.borrower,\n params.liquidator,\n vars.actualCollateralToLiquidate,\n collateralReserveCache.nextLiquidityIndex\n );\n }\n\n /**\n * @notice Burns the collateral xTokens and transfers the underlying to the liquidator.\n * @dev The function also updates the state and the interest rate of the collateral reserve.\n * @param params The additional parameters needed to execute the liquidation function\n * @param vars The executeLiquidateERC20() function local vars\n */\n function _burnCollateralNTokens(\n DataTypes.ExecuteLiquidateParams memory params,\n ExecuteLiquidateLocalVars memory vars\n ) internal {\n // Burn the equivalent amount of xToken, sending the underlying to the liquidator\n uint256[] memory tokenIds = new uint256[](1);\n tokenIds[0] = params.collateralTokenId;\n INToken(vars.collateralXToken).burn(\n params.borrower,\n params.liquidator,\n tokenIds\n );\n }\n\n /**\n * @notice Liquidates the user xTokens by transferring them to the liquidator.\n * @dev The function also checks the state of the liquidator and activates the xToken as collateral\n * as in standard transfers if the isolation mode constraints are respected.\n * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n * @param collateralReserve The data of the collateral reserve\n * @param params The additional parameters needed to execute the liquidation function\n * @param vars The executeLiquidateERC20() function local vars\n */\n function _liquidatePTokens(\n mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n DataTypes.ReserveData storage collateralReserve,\n DataTypes.ExecuteLiquidateParams memory params,\n ExecuteLiquidateLocalVars memory vars\n ) internal {\n IPToken pToken = IPToken(vars.collateralXToken);\n uint256 liquidatorPreviousPTokenBalance = pToken.balanceOf(\n params.liquidator\n );\n pToken.transferOnLiquidation(\n params.borrower,\n params.liquidator,\n vars.actualCollateralToLiquidate\n );\n\n if (liquidatorPreviousPTokenBalance == 0) {\n DataTypes.UserConfigurationMap\n storage liquidatorConfig = usersConfig[params.liquidator];\n\n liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true);\n emit ReserveUsedAsCollateralEnabled(\n params.collateralAsset,\n params.liquidator\n );\n }\n }\n\n /**\n * @notice Burns the debt tokens of the user up to the amount being repaid by the liquidator.\n * @dev The function alters the `liquidationAssetReserveCache` state in `vars` to update the debt related data.\n * @param liquidationAssetReserve The data of the liquidation reserve\n * @param params The additional parameters needed to execute the liquidation function\n * @param vars the executeLiquidateERC20() function local vars\n */\n function _burnDebtTokens(\n DataTypes.ReserveData storage liquidationAssetReserve,\n DataTypes.ExecuteLiquidateParams memory params,\n ExecuteLiquidateLocalVars memory vars\n ) internal {\n _depositETH(params, vars);\n // Handle payment\n IPToken(vars.liquidationAssetReserveCache.xTokenAddress)\n .handleRepayment(params.liquidator, vars.actualLiquidationAmount);\n // Burn borrower's debt token\n vars\n .liquidationAssetReserveCache\n .nextScaledVariableDebt = IVariableDebtToken(\n vars.liquidationAssetReserveCache.variableDebtTokenAddress\n ).burn(\n params.borrower,\n vars.actualLiquidationAmount,\n vars.liquidationAssetReserveCache.nextVariableBorrowIndex\n );\n // Update borrow & supply rate\n liquidationAssetReserve.updateInterestRates(\n vars.liquidationAssetReserveCache,\n params.liquidationAsset,\n vars.actualLiquidationAmount,\n 0\n );\n // Transfers the debt asset being repaid to the xToken, where the liquidity is kept\n IERC20(params.liquidationAsset).safeTransferFrom(\n vars.payer,\n vars.liquidationAssetReserveCache.xTokenAddress,\n vars.actualLiquidationAmount\n );\n }\n\n /**\n * @notice Supply new collateral for taking out of borrower's another collateral\n * @param userConfig The user configuration that track the supplied/borrowed assets\n * @param params The additional parameters needed to execute the liquidation function\n * @param vars the executeLiquidateERC20() function local vars\n */\n function _supplyNewCollateral(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteLiquidateParams memory params,\n ExecuteLiquidateLocalVars memory vars\n ) internal {\n _depositETH(params, vars);\n\n SupplyLogic.executeSupply(\n reservesData,\n userConfig,\n DataTypes.ExecuteSupplyParams({\n asset: params.liquidationAsset,\n amount: vars.actualLiquidationAmount -\n vars.liquidationProtocolFee,\n onBehalfOf: params.borrower,\n payer: vars.payer,\n referralCode: 0\n })\n );\n\n if (!userConfig.isUsingAsCollateral(vars.liquidationAssetReserveId)) {\n userConfig.setUsingAsCollateral(\n vars.liquidationAssetReserveId,\n true\n );\n emit ReserveUsedAsCollateralEnabled(\n params.liquidationAsset,\n params.borrower\n );\n }\n }\n\n /**\n * @notice Calculates the total debt of the user and the actual amount to liquidate depending on the health factor\n * and corresponding close factor. we are always using max closing factor in this version\n * @param params The additional parameters needed to execute the liquidation function\n * @param vars the executeLiquidateERC20() function local vars\n * @return The total debt of the user\n * @return The actual debt that is getting liquidated. If liquidation amount passed in by the liquidator is greater then the total user debt, then use the user total debt as the actual debt getting liquidated. If the user total debt is greater than the liquidation amount getting passed in by the liquidator, then use the liquidation amount the user is passing in.\n */\n function _calculateDebt(\n DataTypes.ExecuteLiquidateParams memory params,\n ExecuteLiquidateLocalVars memory vars\n ) internal view returns (uint256, uint256) {\n // userDebt = debt of the borrowed position needed for liquidation\n uint256 userDebt = Helpers.getUserCurrentDebt(\n params.borrower,\n vars.liquidationAssetReserveCache.variableDebtTokenAddress\n );\n\n uint256 closeFactor = vars.healthFactor > CLOSE_FACTOR_HF_THRESHOLD\n ? DEFAULT_LIQUIDATION_CLOSE_FACTOR\n : MAX_LIQUIDATION_CLOSE_FACTOR;\n\n uint256 maxLiquidatableDebt = userDebt.percentMul(closeFactor);\n\n uint256 actualLiquidationAmount = Math.min(\n params.liquidationAmount,\n maxLiquidatableDebt\n );\n\n return (userDebt, actualLiquidationAmount);\n }\n\n /**\n * @notice Returns the configuration data for the debt and the collateral reserves.\n * @param collateralReserve The data of the collateral reserve\n * @return The collateral xToken\n * @return The liquidation bonus to apply to the collateral\n */\n function _getConfigurationData(\n DataTypes.ReserveData storage collateralReserve\n ) internal view returns (address, uint256) {\n address collateralXToken = collateralReserve.xTokenAddress;\n uint256 liquidationBonus = collateralReserve\n .configuration\n .getLiquidationBonus();\n\n return (collateralXToken, liquidationBonus);\n }\n\n /**\n * @notice Calculates how much of a specific collateral can be liquidated, given\n * a certain amount of debt asset.\n * @dev This function needs to be called after all the checks to validate the liquidation have been performed,\n * otherwise it might fail.\n * @param collateralReserve The data of the collateral reserve\n * @param params The additional parameters needed to execute the liquidation function\n * @param superVars the executeLiquidateERC20() function local vars\n * @return The user collateral balance\n * @return The maximum amount that is possible to liquidate given all the liquidation constraints (user balance, close factor)\n * @return The amount to repay with the liquidation\n * @return The fee taken from the liquidation bonus amount to be paid to the protocol\n **/\n function _calculateERC20LiquidationParameters(\n DataTypes.ReserveData storage collateralReserve,\n DataTypes.ExecuteLiquidateParams memory params,\n ExecuteLiquidateLocalVars memory superVars\n )\n internal\n view\n returns (\n uint256,\n uint256,\n uint256,\n uint256\n )\n {\n LiquidateParametersLocalVars memory vars;\n\n vars.userCollateral = IPToken(superVars.collateralXToken).balanceOf(\n params.borrower\n );\n vars.collateralPrice = IPriceOracleGetter(params.priceOracle)\n .getAssetPrice(params.collateralAsset);\n vars.liquidationAssetPrice = IPriceOracleGetter(params.priceOracle)\n .getAssetPrice(params.liquidationAsset);\n\n vars.collateralDecimals = collateralReserve.configuration.getDecimals();\n vars.liquidationAssetDecimals = superVars\n .liquidationAssetReserveCache\n .reserveConfiguration\n .getDecimals();\n\n unchecked {\n vars.collateralAssetUnit = 10**vars.collateralDecimals;\n vars.liquidationAssetUnit = 10**vars.liquidationAssetDecimals;\n }\n\n vars.liquidationProtocolFeePercentage = collateralReserve\n .configuration\n .getLiquidationProtocolFee();\n\n uint256 maxCollateralToLiquidate = ((vars.liquidationAssetPrice *\n superVars.actualLiquidationAmount *\n vars.collateralAssetUnit) /\n (vars.collateralPrice * vars.liquidationAssetUnit)).percentMul(\n superVars.liquidationBonus\n );\n\n if (maxCollateralToLiquidate > vars.userCollateral) {\n vars.actualCollateralToLiquidate = vars.userCollateral;\n vars.actualLiquidationAmount = (\n ((vars.collateralPrice *\n vars.actualCollateralToLiquidate *\n vars.liquidationAssetUnit) /\n (vars.liquidationAssetPrice * vars.collateralAssetUnit))\n ).percentDiv(superVars.liquidationBonus);\n } else {\n vars.actualCollateralToLiquidate = maxCollateralToLiquidate;\n vars.actualLiquidationAmount = superVars.actualLiquidationAmount;\n }\n\n if (vars.liquidationProtocolFeePercentage != 0) {\n uint256 bonusCollateral = vars.actualCollateralToLiquidate -\n vars.actualCollateralToLiquidate.percentDiv(\n superVars.liquidationBonus\n );\n\n vars.liquidationProtocolFee = bonusCollateral.percentMul(\n vars.liquidationProtocolFeePercentage\n );\n\n return (\n vars.userCollateral,\n vars.actualCollateralToLiquidate - vars.liquidationProtocolFee,\n vars.actualLiquidationAmount,\n vars.liquidationProtocolFee\n );\n } else {\n return (\n vars.userCollateral,\n vars.actualCollateralToLiquidate,\n vars.actualLiquidationAmount,\n 0\n );\n }\n }\n\n /**\n * @notice Calculates how much of a specific collateral can be liquidated, given\n * a certain amount of debt asset.\n * @dev This function needs to be called after all the checks to validate the liquidation have been performed,\n * otherwise it might fail.\n * @param collateralReserve The data of the collateral reserve\n * @param params The additional parameters needed to execute the liquidation function\n * @param superVars the executeLiquidateERC20() function local vars\n * @return The user collateral balance\n * @return The discounted nft price + the liquidationProtocolFee\n * @return The liquidationProtocolFee\n * @return The debt price you are paying in (for example, USD or ETH)\n **/\n function _calculateERC721LiquidationParameters(\n DataTypes.ReserveData storage collateralReserve,\n DataTypes.ExecuteLiquidateParams memory params,\n ExecuteLiquidateLocalVars memory superVars\n )\n internal\n view\n returns (\n uint256,\n uint256,\n uint256,\n uint256\n )\n {\n LiquidateParametersLocalVars memory vars;\n\n vars.userCollateral = ICollateralizableERC721(\n superVars.collateralXToken\n ).collateralizedBalanceOf(params.borrower);\n\n // price of the asset that is used as collateral\n if (INToken(superVars.collateralXToken).getAtomicPricingConfig()) {\n vars.collateralPrice = IPriceOracleGetter(params.priceOracle)\n .getTokenPrice(\n params.collateralAsset,\n params.collateralTokenId\n );\n } else {\n vars.collateralPrice = IPriceOracleGetter(params.priceOracle)\n .getAssetPrice(params.collateralAsset);\n }\n\n if (\n superVars.auctionEnabled &&\n IAuctionableERC721(superVars.collateralXToken).isAuctioned(\n params.collateralTokenId\n )\n ) {\n vars.auctionStartTime = IAuctionableERC721(\n superVars.collateralXToken\n ).getAuctionData(params.collateralTokenId).startTime;\n vars.auctionMultiplier = IReserveAuctionStrategy(\n superVars.auctionStrategyAddress\n ).calculateAuctionPriceMultiplier(\n vars.auctionStartTime,\n block.timestamp\n );\n vars.collateralPrice = vars.collateralPrice.mul(\n vars.auctionMultiplier\n );\n }\n\n // price of the asset the liquidator is liquidating with\n vars.liquidationAssetPrice = IPriceOracleGetter(params.priceOracle)\n .getAssetPrice(params.liquidationAsset);\n vars.liquidationAssetDecimals = superVars\n .liquidationAssetReserveCache\n .reserveConfiguration\n .getDecimals();\n\n unchecked {\n vars.liquidationAssetUnit = 10**vars.liquidationAssetDecimals;\n }\n\n vars.liquidationProtocolFeePercentage = collateralReserve\n .configuration\n .getLiquidationProtocolFee();\n\n uint256 collateralToLiquidate = (vars.collateralPrice *\n vars.liquidationAssetUnit) / vars.liquidationAssetPrice;\n\n // base currency to convert to liquidation asset unit.\n uint256 globalDebtAmount = (superVars.userGlobalDebt *\n vars.liquidationAssetUnit) / vars.liquidationAssetPrice;\n\n vars.actualLiquidationAmount = collateralToLiquidate.percentDiv(\n superVars.liquidationBonus\n );\n\n if (vars.liquidationProtocolFeePercentage != 0) {\n uint256 bonusCollateral = collateralToLiquidate -\n vars.actualLiquidationAmount;\n\n vars.liquidationProtocolFee = bonusCollateral.percentMul(\n vars.liquidationProtocolFeePercentage\n );\n\n return (\n vars.userCollateral,\n vars.actualLiquidationAmount + vars.liquidationProtocolFee,\n vars.liquidationProtocolFee,\n globalDebtAmount\n );\n } else {\n return (\n vars.userCollateral,\n vars.actualLiquidationAmount,\n 0,\n globalDebtAmount\n );\n }\n }\n\n /**\n * @notice Convert msg.value to WETH and check if liquidationAsset is WETH (if msg.value > 0)\n * @param params The additional parameters needed to execute the liquidation function\n * @param vars the executeLiquidateERC20() function local vars\n */\n function _depositETH(\n DataTypes.ExecuteLiquidateParams memory params,\n ExecuteLiquidateLocalVars memory vars\n ) internal {\n if (msg.value == 0) {\n vars.payer = msg.sender;\n } else {\n vars.payer = address(this);\n IWETH(params.weth).deposit{value: vars.actualLiquidationAmount}();\n if (msg.value > vars.actualLiquidationAmount) {\n Address.sendValue(\n payable(msg.sender),\n msg.value - vars.actualLiquidationAmount\n );\n }\n }\n }\n}\n" }, "contracts/protocol/libraries/logic/AuctionLogic.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {DataTypes} from \"../../libraries/types/DataTypes.sol\";\nimport {ValidationLogic} from \"./ValidationLogic.sol\";\nimport {GenericLogic} from \"./GenericLogic.sol\";\nimport {IAuctionableERC721} from \"../../../interfaces/IAuctionableERC721.sol\";\nimport {IReserveAuctionStrategy} from \"../../../interfaces/IReserveAuctionStrategy.sol\";\n\n/**\n * @title AuctionLogic library\n *\n * @notice Implements actions involving NFT auctions\n **/\nlibrary AuctionLogic {\n event AuctionStarted(\n address indexed user,\n address indexed collateralAsset,\n uint256 indexed collateralTokenId\n );\n event AuctionEnded(\n address indexed user,\n address indexed collateralAsset,\n uint256 indexed collateralTokenId\n );\n\n struct AuctionLocalVars {\n uint256 erc721HealthFactor;\n address collateralXToken;\n DataTypes.AssetType assetType;\n }\n\n /**\n * @notice Function to tsatr auction on an ERC721 of a position if its ERC721 Health Factor drops below 1.\n * @dev Emits the `AuctionStarted()` event\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n * @param params The additional parameters needed to execute the auction function\n **/\n function executeStartAuction(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n DataTypes.ExecuteAuctionParams memory params\n ) external {\n AuctionLocalVars memory vars;\n DataTypes.ReserveData storage collateralReserve = reservesData[\n params.collateralAsset\n ];\n\n vars.collateralXToken = collateralReserve.xTokenAddress;\n DataTypes.UserConfigurationMap storage userConfig = usersConfig[\n params.user\n ];\n\n (, , , , , , , , vars.erc721HealthFactor, ) = GenericLogic\n .calculateUserAccountData(\n reservesData,\n reservesList,\n DataTypes.CalculateUserAccountDataParams({\n userConfig: userConfig,\n reservesCount: params.reservesCount,\n user: params.user,\n oracle: params.priceOracle\n })\n );\n\n ValidationLogic.validateStartAuction(\n userConfig,\n collateralReserve,\n DataTypes.ValidateAuctionParams({\n user: params.user,\n auctionRecoveryHealthFactor: params.auctionRecoveryHealthFactor,\n erc721HealthFactor: vars.erc721HealthFactor,\n collateralAsset: params.collateralAsset,\n tokenId: params.collateralTokenId,\n xTokenAddress: vars.collateralXToken\n })\n );\n\n IAuctionableERC721(vars.collateralXToken).startAuction(\n params.collateralTokenId\n );\n\n emit AuctionStarted(\n params.user,\n params.collateralAsset,\n params.collateralTokenId\n );\n }\n\n /**\n * @notice Function to end auction on an ERC721 of a position if its ERC721 Health Factor increases back to above `AUCTION_RECOVERY_HEALTH_FACTOR`.\n * @dev Emits the `AuctionEnded()` event\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n * @param params The additional parameters needed to execute the auction function\n **/\n function executeEndAuction(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n DataTypes.ExecuteAuctionParams memory params\n ) external {\n AuctionLocalVars memory vars;\n DataTypes.ReserveData storage collateralReserve = reservesData[\n params.collateralAsset\n ];\n vars.collateralXToken = collateralReserve.xTokenAddress;\n DataTypes.UserConfigurationMap storage userConfig = usersConfig[\n params.user\n ];\n\n (, , , , , , , , vars.erc721HealthFactor, ) = GenericLogic\n .calculateUserAccountData(\n reservesData,\n reservesList,\n DataTypes.CalculateUserAccountDataParams({\n userConfig: userConfig,\n reservesCount: params.reservesCount,\n user: params.user,\n oracle: params.priceOracle\n })\n );\n\n ValidationLogic.validateEndAuction(\n collateralReserve,\n DataTypes.ValidateAuctionParams({\n user: params.user,\n auctionRecoveryHealthFactor: params.auctionRecoveryHealthFactor,\n erc721HealthFactor: vars.erc721HealthFactor,\n collateralAsset: params.collateralAsset,\n tokenId: params.collateralTokenId,\n xTokenAddress: vars.collateralXToken\n })\n );\n\n IAuctionableERC721(vars.collateralXToken).endAuction(\n params.collateralTokenId\n );\n\n emit AuctionEnded(\n params.user,\n params.collateralAsset,\n params.collateralTokenId\n );\n }\n}\n" }, "contracts/protocol/libraries/types/DataTypes.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {OfferItem, ConsiderationItem} from \"../../../dependencies/seaport/contracts/lib/ConsiderationStructs.sol\";\n\nlibrary DataTypes {\n enum AssetType {\n ERC20,\n ERC721\n }\n\n address public constant SApeAddress = address(0x1);\n uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;\n\n struct ReserveData {\n //stores the reserve configuration\n ReserveConfigurationMap configuration;\n //the liquidity index. Expressed in ray\n uint128 liquidityIndex;\n //the current supply rate. Expressed in ray\n uint128 currentLiquidityRate;\n //variable borrow index. Expressed in ray\n uint128 variableBorrowIndex;\n //the current variable borrow rate. Expressed in ray\n uint128 currentVariableBorrowRate;\n //timestamp of last update\n uint40 lastUpdateTimestamp;\n //the id of the reserve. Represents the position in the list of the active reserves\n uint16 id;\n //xToken address\n address xTokenAddress;\n //variableDebtToken address\n address variableDebtTokenAddress;\n //address of the interest rate strategy\n address interestRateStrategyAddress;\n //address of the auction strategy\n address auctionStrategyAddress;\n //the current treasury balance, scaled\n uint128 accruedToTreasury;\n }\n\n struct ReserveConfigurationMap {\n //bit 0-15: LTV\n //bit 16-31: Liq. threshold\n //bit 32-47: Liq. bonus\n //bit 48-55: Decimals\n //bit 56: reserve is active\n //bit 57: reserve is frozen\n //bit 58: borrowing is enabled\n //bit 59: stable rate borrowing enabled\n //bit 60: asset is paused\n //bit 61: borrowing in isolation mode is enabled\n //bit 62-63: reserved\n //bit 64-79: reserve factor\n //bit 80-115 borrow cap in whole tokens, borrowCap == 0 => no cap\n //bit 116-151 supply cap in whole tokens, supplyCap == 0 => no cap\n //bit 152-167 liquidation protocol fee\n //bit 168-175 eMode category\n //bit 176-211 unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled\n //bit 212-251 debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals\n //bit 252-255 unused\n\n uint256 data;\n }\n\n struct UserConfigurationMap {\n /**\n * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.\n * The first bit indicates if an asset is used as collateral by the user, the second whether an\n * asset is borrowed by the user.\n */\n uint256 data;\n // auction validity time for closing invalid auctions in one tx.\n uint256 auctionValidityTime;\n }\n\n struct ERC721SupplyParams {\n uint256 tokenId;\n bool useAsCollateral;\n }\n\n struct NTokenData {\n uint256 tokenId;\n bool useAsCollateral;\n bool isAuctioned;\n }\n\n struct ReserveCache {\n uint256 currScaledVariableDebt;\n uint256 nextScaledVariableDebt;\n uint256 currLiquidityIndex;\n uint256 nextLiquidityIndex;\n uint256 currVariableBorrowIndex;\n uint256 nextVariableBorrowIndex;\n uint256 currLiquidityRate;\n uint256 currVariableBorrowRate;\n uint256 reserveFactor;\n ReserveConfigurationMap reserveConfiguration;\n address xTokenAddress;\n address variableDebtTokenAddress;\n uint40 reserveLastUpdateTimestamp;\n }\n\n struct ExecuteLiquidateParams {\n uint256 reservesCount;\n uint256 liquidationAmount;\n uint256 collateralTokenId;\n uint256 auctionRecoveryHealthFactor;\n address weth;\n address collateralAsset;\n address liquidationAsset;\n address borrower;\n address liquidator;\n bool receiveXToken;\n address priceOracle;\n address priceOracleSentinel;\n }\n\n struct ExecuteAuctionParams {\n uint256 reservesCount;\n uint256 auctionRecoveryHealthFactor;\n uint256 collateralTokenId;\n address collateralAsset;\n address user;\n address priceOracle;\n }\n\n struct ExecuteSupplyParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n address payer;\n uint16 referralCode;\n }\n\n struct ExecuteSupplyERC721Params {\n address asset;\n DataTypes.ERC721SupplyParams[] tokenData;\n address onBehalfOf;\n address payer;\n uint16 referralCode;\n }\n\n struct ExecuteBorrowParams {\n address asset;\n address user;\n address onBehalfOf;\n uint256 amount;\n uint16 referralCode;\n bool releaseUnderlying;\n uint256 reservesCount;\n address oracle;\n address priceOracleSentinel;\n }\n\n struct ExecuteRepayParams {\n address asset;\n uint256 amount;\n address onBehalfOf;\n bool usePTokens;\n }\n\n struct ExecuteWithdrawParams {\n address asset;\n uint256 amount;\n address to;\n uint256 reservesCount;\n address oracle;\n }\n\n struct ExecuteWithdrawERC721Params {\n address asset;\n uint256[] tokenIds;\n address to;\n uint256 reservesCount;\n address oracle;\n }\n\n struct ExecuteDecreaseUniswapV3LiquidityParams {\n address user;\n address asset;\n uint256 tokenId;\n uint256 reservesCount;\n uint128 liquidityDecrease;\n uint256 amount0Min;\n uint256 amount1Min;\n bool receiveEthAsWeth;\n address oracle;\n }\n\n struct FinalizeTransferParams {\n address asset;\n address from;\n address to;\n bool usedAsCollateral;\n uint256 amount;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n }\n\n struct FinalizeTransferERC721Params {\n address asset;\n address from;\n address to;\n bool usedAsCollateral;\n uint256 tokenId;\n uint256 balanceFromBefore;\n uint256 balanceToBefore;\n uint256 reservesCount;\n address oracle;\n }\n\n struct CalculateUserAccountDataParams {\n UserConfigurationMap userConfig;\n uint256 reservesCount;\n address user;\n address oracle;\n }\n\n struct ValidateBorrowParams {\n ReserveCache reserveCache;\n UserConfigurationMap userConfig;\n address asset;\n address userAddress;\n uint256 amount;\n uint256 reservesCount;\n address oracle;\n address priceOracleSentinel;\n }\n\n struct ValidateLiquidateERC20Params {\n ReserveCache liquidationAssetReserveCache;\n address liquidationAsset;\n address weth;\n uint256 totalDebt;\n uint256 healthFactor;\n uint256 liquidationAmount;\n uint256 actualLiquidationAmount;\n address priceOracleSentinel;\n }\n\n struct ValidateLiquidateERC721Params {\n ReserveCache liquidationAssetReserveCache;\n address liquidator;\n address borrower;\n uint256 globalDebt;\n uint256 healthFactor;\n address collateralAsset;\n uint256 tokenId;\n uint256 actualLiquidationAmount;\n uint256 maxLiquidationAmount;\n uint256 auctionRecoveryHealthFactor;\n address priceOracleSentinel;\n address xTokenAddress;\n bool auctionEnabled;\n }\n\n struct ValidateAuctionParams {\n address user;\n uint256 auctionRecoveryHealthFactor;\n uint256 erc721HealthFactor;\n address collateralAsset;\n uint256 tokenId;\n address xTokenAddress;\n }\n\n struct CalculateInterestRatesParams {\n uint256 liquidityAdded;\n uint256 liquidityTaken;\n uint256 totalVariableDebt;\n uint256 reserveFactor;\n address reserve;\n address xToken;\n }\n\n struct InitReserveParams {\n address asset;\n address xTokenAddress;\n address variableDebtAddress;\n address interestRateStrategyAddress;\n address auctionStrategyAddress;\n uint16 reservesCount;\n uint16 maxNumberReserves;\n }\n\n struct ExecuteFlashClaimParams {\n address receiverAddress;\n address nftAsset;\n uint256[] nftTokenIds;\n bytes params;\n address oracle;\n }\n\n struct Credit {\n address token;\n uint256 amount;\n bytes orderId;\n uint8 v;\n bytes32 r;\n bytes32 s;\n }\n\n struct ExecuteMarketplaceParams {\n bytes32 marketplaceId;\n bytes payload;\n Credit credit;\n uint256 ethLeft;\n DataTypes.Marketplace marketplace;\n OrderInfo orderInfo;\n address weth;\n uint16 referralCode;\n uint256 reservesCount;\n address oracle;\n address priceOracleSentinel;\n }\n\n struct OrderInfo {\n address maker;\n address taker;\n bytes id;\n OfferItem[] offer;\n ConsiderationItem[] consideration;\n }\n\n struct Marketplace {\n address marketplace;\n address adapter;\n address operator;\n bool paused;\n }\n\n struct Auction {\n uint256 startTime;\n }\n\n struct AuctionData {\n address asset;\n uint256 tokenId;\n uint256 startTime;\n uint256 currentPriceMultiplier;\n uint256 maxPriceMultiplier;\n uint256 minExpPriceMultiplier;\n uint256 minPriceMultiplier;\n uint256 stepLinear;\n uint256 stepExp;\n uint256 tickLength;\n }\n\n struct TokenData {\n string symbol;\n address tokenAddress;\n }\n\n struct PoolStorage {\n // Map of reserves and their data (underlyingAssetOfReserve => reserveData)\n mapping(address => ReserveData) _reserves;\n // Map of users address and their configuration data (userAddress => userConfiguration)\n mapping(address => UserConfigurationMap) _usersConfig;\n // List of reserves as a map (reserveId => reserve).\n // It is structured as a mapping for gas savings reasons, using the reserve id as index\n mapping(uint256 => address) _reservesList;\n // Maximum number of active reserves there have been in the protocol. It is the upper bound of the reserves list\n uint16 _reservesCount;\n // Auction recovery health factor\n uint64 _auctionRecoveryHealthFactor;\n }\n\n struct ReserveConfigData {\n uint256 decimals;\n uint256 ltv;\n uint256 liquidationThreshold;\n uint256 liquidationBonus;\n uint256 reserveFactor;\n bool usageAsCollateralEnabled;\n bool borrowingEnabled;\n bool isActive;\n bool isFrozen;\n bool isPaused;\n }\n}\n" }, "contracts/protocol/libraries/logic/FlashClaimLogic.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {IERC721} from \"../../../dependencies/openzeppelin/contracts/IERC721.sol\";\nimport {IFlashClaimReceiver} from \"../../../misc/interfaces/IFlashClaimReceiver.sol\";\nimport {INToken} from \"../../../interfaces/INToken.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {ValidationLogic} from \"./ValidationLogic.sol\";\nimport \"../../../interfaces/INTokenApeStaking.sol\";\nimport {XTokenType, IXTokenType} from \"../../../interfaces/IXTokenType.sol\";\nimport {GenericLogic} from \"./GenericLogic.sol\";\n\nlibrary FlashClaimLogic {\n // See `IPool` for descriptions\n event FlashClaim(\n address indexed target,\n address indexed initiator,\n address indexed nftAsset,\n uint256 tokenId\n );\n\n /**\n * @notice Implements the executeFlashClaim feature.\n * @param ps The state of pool storage\n * @param params The additional parameters needed to execute the flash claim\n */\n function executeFlashClaim(\n DataTypes.PoolStorage storage ps,\n DataTypes.ExecuteFlashClaimParams memory params\n ) external {\n DataTypes.ReserveData storage reserve = ps._reserves[params.nftAsset];\n address nTokenAddress = reserve.xTokenAddress;\n ValidationLogic.validateFlashClaim(ps, params);\n\n uint256 i;\n // step 1: moving underlying asset forward to receiver contract\n for (i = 0; i < params.nftTokenIds.length; i++) {\n INToken(nTokenAddress).transferUnderlyingTo(\n params.receiverAddress,\n params.nftTokenIds[i]\n );\n }\n\n // step 2: execute receiver contract, doing something like airdrop\n require(\n IFlashClaimReceiver(params.receiverAddress).executeOperation(\n params.nftAsset,\n params.nftTokenIds,\n params.params\n ),\n Errors.INVALID_FLASH_CLAIM_RECEIVER\n );\n\n // step 3: moving underlying asset backward from receiver contract\n for (i = 0; i < params.nftTokenIds.length; i++) {\n IERC721(params.nftAsset).safeTransferFrom(\n params.receiverAddress,\n nTokenAddress,\n params.nftTokenIds[i]\n );\n\n emit FlashClaim(\n params.receiverAddress,\n msg.sender,\n params.nftAsset,\n params.nftTokenIds[i]\n );\n }\n\n // step 4: check hf\n DataTypes.CalculateUserAccountDataParams\n memory accountParams = DataTypes.CalculateUserAccountDataParams({\n userConfig: ps._usersConfig[msg.sender],\n reservesCount: ps._reservesCount,\n user: msg.sender,\n oracle: params.oracle\n });\n\n (, , , , , , , uint256 healthFactor, , ) = GenericLogic\n .calculateUserAccountData(\n ps._reserves,\n ps._reservesList,\n accountParams\n );\n require(\n healthFactor > DataTypes.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n );\n }\n}\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/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/protocol/libraries/paraspace-upgradeability/ParaReentrancyGuard.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.10;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ParaReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 constant _NOT_ENTERED = 1;\n uint256 constant _ENTERED = 2;\n\n bytes32 constant RG_STORAGE_POSITION =\n bytes32(uint256(keccak256(\"paraspace.proxy.rg.storage\")) - 1);\n\n struct RGStorage {\n uint256 _status;\n }\n\n function rgStorage() internal pure returns (RGStorage storage rgs) {\n bytes32 position = RG_STORAGE_POSITION;\n assembly {\n rgs.slot := position\n }\n }\n\n // constructor() {\n // _status = _NOT_ENTERED;\n // }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and make it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n RGStorage storage rgs = rgStorage();\n // On the first call to nonReentrant, _notEntered will be true\n require(rgs._status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n rgs._status = _ENTERED;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n rgs._status = _NOT_ENTERED;\n }\n}\n" }, "contracts/protocol/libraries/logic/SupplyLogic.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {IERC20} from \"../../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {IERC721} from \"../../../dependencies/openzeppelin/contracts/IERC721.sol\";\nimport {GPv2SafeERC20} from \"../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol\";\nimport {IPToken} from \"../../../interfaces/IPToken.sol\";\nimport {INonfungiblePositionManager} from \"../../../dependencies/uniswap/INonfungiblePositionManager.sol\";\nimport {INToken} from \"../../../interfaces/INToken.sol\";\nimport {INTokenApeStaking} from \"../../../interfaces/INTokenApeStaking.sol\";\nimport {ICollateralizableERC721} from \"../../../interfaces/ICollateralizableERC721.sol\";\nimport {IAuctionableERC721} from \"../../../interfaces/IAuctionableERC721.sol\";\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {UserConfiguration} from \"../configuration/UserConfiguration.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {WadRayMath} from \"../math/WadRayMath.sol\";\nimport {PercentageMath} from \"../math/PercentageMath.sol\";\nimport {ValidationLogic} from \"./ValidationLogic.sol\";\nimport {ReserveLogic} from \"./ReserveLogic.sol\";\nimport {XTokenType} from \"../../../interfaces/IXTokenType.sol\";\nimport {INTokenUniswapV3} from \"../../../interfaces/INTokenUniswapV3.sol\";\n\n/**\n * @title SupplyLogic library\n *\n * @notice Implements the base logic for supply/withdraw\n */\nlibrary SupplyLogic {\n using ReserveLogic for DataTypes.ReserveData;\n using GPv2SafeERC20 for IERC20;\n using UserConfiguration for DataTypes.UserConfigurationMap;\n using WadRayMath for uint256;\n\n // See `IPool` for descriptions\n event ReserveUsedAsCollateralEnabled(\n address indexed reserve,\n address indexed user\n );\n event ReserveUsedAsCollateralDisabled(\n address indexed reserve,\n address indexed user\n );\n event Supply(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n uint256 amount,\n uint16 indexed referralCode\n );\n event Withdraw(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256 amount\n );\n event SupplyERC721(\n address indexed reserve,\n address user,\n address indexed onBehalfOf,\n DataTypes.ERC721SupplyParams[] tokenData,\n uint16 indexed referralCode,\n bool fromNToken\n );\n\n event WithdrawERC721(\n address indexed reserve,\n address indexed user,\n address indexed to,\n uint256[] tokenIds\n );\n\n /**\n * @notice Implements the supply feature. Through `supply()`, users supply assets to the ParaSpace protocol.\n * @dev Emits the `Supply()` event.\n * @dev In the first supply action, `ReserveUsedAsCollateralEnabled()` is emitted, if the asset can be enabled as\n * collateral.\n * @param reservesData The state of all the reserves\n * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n * @param params The additional parameters needed to execute the supply function\n */\n function executeSupply(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteSupplyParams memory params\n ) external {\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n reserve.updateState(reserveCache);\n\n ValidationLogic.validateSupply(\n reserveCache,\n params.amount,\n DataTypes.AssetType.ERC20\n );\n\n reserve.updateInterestRates(\n reserveCache,\n params.asset,\n params.amount,\n 0\n );\n\n IERC20(params.asset).safeTransferFrom(\n params.payer,\n reserveCache.xTokenAddress,\n params.amount\n );\n\n bool isFirstSupply = IPToken(reserveCache.xTokenAddress).mint(\n msg.sender,\n params.onBehalfOf,\n params.amount,\n reserveCache.nextLiquidityIndex\n );\n\n if (isFirstSupply) {\n userConfig.setUsingAsCollateral(reserve.id, true);\n emit ReserveUsedAsCollateralEnabled(\n params.asset,\n params.onBehalfOf\n );\n }\n\n emit Supply(\n params.asset,\n msg.sender,\n params.onBehalfOf,\n params.amount,\n params.referralCode\n );\n }\n\n function executeSupplyERC721Base(\n uint16 reserveId,\n address nTokenAddress,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteSupplyERC721Params memory params\n ) internal {\n //currently don't need to update state for erc721\n //reserve.updateState(reserveCache);\n\n (\n uint64 oldCollateralizedBalance,\n uint64 newCollateralizedBalance\n ) = INToken(nTokenAddress).mint(params.onBehalfOf, params.tokenData);\n bool isFirstSupplyCollateral = (oldCollateralizedBalance == 0 &&\n newCollateralizedBalance > 0);\n if (isFirstSupplyCollateral) {\n userConfig.setUsingAsCollateral(reserveId, true);\n emit ReserveUsedAsCollateralEnabled(\n params.asset,\n params.onBehalfOf\n );\n }\n }\n\n /**\n * @notice Implements the supplyERC721 feature.\n * @dev Emits the `SupplyERC721()` event.\n * @dev In the first supply action, `ReserveUsedAsCollateralEnabled()` is emitted, if the asset can be enabled as\n * collateral.\n * @param reservesData The state of all the reserves\n * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n * @param params The additional parameters needed to execute the supply function\n */\n function executeSupplyERC721(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteSupplyERC721Params memory params\n ) external {\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n ValidationLogic.validateSupply(\n reserveCache,\n params.tokenData.length,\n DataTypes.AssetType.ERC721\n );\n\n XTokenType tokenType = INToken(reserveCache.xTokenAddress)\n .getXTokenType();\n if (tokenType == XTokenType.NTokenUniswapV3) {\n for (uint256 index = 0; index < params.tokenData.length; index++) {\n ValidationLogic.validateForUniswapV3(\n reservesData,\n params.asset,\n params.tokenData[index].tokenId,\n true,\n true,\n true\n );\n }\n }\n if (\n tokenType == XTokenType.NTokenBAYC ||\n tokenType == XTokenType.NTokenMAYC\n ) {\n uint16 sApeReserveId = reservesData[DataTypes.SApeAddress].id;\n bool currentStatus = userConfig.isUsingAsCollateral(sApeReserveId);\n if (!currentStatus) {\n userConfig.setUsingAsCollateral(sApeReserveId, true);\n emit ReserveUsedAsCollateralEnabled(\n DataTypes.SApeAddress,\n params.onBehalfOf\n );\n }\n }\n for (uint256 index = 0; index < params.tokenData.length; index++) {\n IERC721(params.asset).safeTransferFrom(\n params.payer,\n reserveCache.xTokenAddress,\n params.tokenData[index].tokenId\n );\n }\n\n executeSupplyERC721Base(\n reserve.id,\n reserveCache.xTokenAddress,\n userConfig,\n params\n );\n\n emit SupplyERC721(\n params.asset,\n msg.sender,\n params.onBehalfOf,\n params.tokenData,\n params.referralCode,\n false\n );\n }\n\n /**\n * @notice Implements the executeSupplyERC721FromNToken feature.\n * @dev Emits the `SupplyERC721()` event with fromNToken as true.\n * @dev same as `executeSupplyERC721` whereas no need to transfer the underlying nft\n * @param reservesData The state of all the reserves\n * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n * @param params The additional parameters needed to execute the supply function\n */\n function executeSupplyERC721FromNToken(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteSupplyERC721Params memory params\n ) external {\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n ValidationLogic.validateSupplyFromNToken(\n reserveCache,\n params,\n DataTypes.AssetType.ERC721\n );\n\n executeSupplyERC721Base(\n reserve.id,\n reserveCache.xTokenAddress,\n userConfig,\n params\n );\n\n emit SupplyERC721(\n params.asset,\n msg.sender,\n params.onBehalfOf,\n params.tokenData,\n params.referralCode,\n true\n );\n }\n\n /**\n * @notice Implements the withdraw feature. Through `withdraw()`, users redeem their xTokens for the underlying asset\n * previously supplied in the ParaSpace protocol.\n * @dev Emits the `Withdraw()` event.\n * @dev If the user withdraws everything, `ReserveUsedAsCollateralDisabled()` is emitted.\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param userConfig The user configuration mapping that tracks the supplied/borrowed assets\n * @param params The additional parameters needed to execute the withdraw function\n * @return The actual amount withdrawn\n */\n function executeWithdraw(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteWithdrawParams memory params\n ) external returns (uint256) {\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n reserve.updateState(reserveCache);\n\n uint256 userBalance = IPToken(reserveCache.xTokenAddress)\n .scaledBalanceOf(msg.sender)\n .rayMul(reserveCache.nextLiquidityIndex);\n\n uint256 amountToWithdraw = params.amount;\n\n if (params.amount == type(uint256).max) {\n amountToWithdraw = userBalance;\n }\n\n ValidationLogic.validateWithdraw(\n reserveCache,\n amountToWithdraw,\n userBalance\n );\n\n reserve.updateInterestRates(\n reserveCache,\n params.asset,\n 0,\n amountToWithdraw\n );\n\n IPToken(reserveCache.xTokenAddress).burn(\n msg.sender,\n params.to,\n amountToWithdraw,\n reserveCache.nextLiquidityIndex\n );\n\n if (userConfig.isUsingAsCollateral(reserve.id)) {\n if (userConfig.isBorrowingAny()) {\n ValidationLogic.validateHFAndLtvERC20(\n reservesData,\n reservesList,\n userConfig,\n params.asset,\n msg.sender,\n params.reservesCount,\n params.oracle\n );\n }\n\n if (amountToWithdraw == userBalance) {\n userConfig.setUsingAsCollateral(reserve.id, false);\n emit ReserveUsedAsCollateralDisabled(params.asset, msg.sender);\n }\n }\n\n emit Withdraw(params.asset, msg.sender, params.to, amountToWithdraw);\n\n return amountToWithdraw;\n }\n\n function executeWithdrawERC721(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteWithdrawERC721Params memory params\n ) external returns (uint256) {\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n //currently don't need to update state for erc721\n //reserve.updateState(reserveCache);\n\n ValidationLogic.validateWithdrawERC721(\n reservesData,\n reserveCache,\n params.asset,\n params.tokenIds\n );\n uint256 amountToWithdraw = params.tokenIds.length;\n\n (\n uint64 oldCollateralizedBalance,\n uint64 newCollateralizedBalance\n ) = INToken(reserveCache.xTokenAddress).burn(\n msg.sender,\n params.to,\n params.tokenIds\n );\n\n bool isWithdrawCollateral = (newCollateralizedBalance <\n oldCollateralizedBalance);\n if (isWithdrawCollateral) {\n if (userConfig.isBorrowingAny()) {\n ValidationLogic.validateHFAndLtvERC721(\n reservesData,\n reservesList,\n userConfig,\n params.asset,\n params.tokenIds,\n msg.sender,\n params.reservesCount,\n params.oracle\n );\n }\n\n if (newCollateralizedBalance == 0) {\n userConfig.setUsingAsCollateral(reserve.id, false);\n emit ReserveUsedAsCollateralDisabled(params.asset, msg.sender);\n }\n }\n\n emit WithdrawERC721(\n params.asset,\n msg.sender,\n params.to,\n params.tokenIds\n );\n\n return amountToWithdraw;\n }\n\n function executeDecreaseUniswapV3Liquidity(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ExecuteDecreaseUniswapV3LiquidityParams memory params\n ) external {\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n //currently don't need to update state for erc721\n //reserve.updateState(reserveCache);\n\n INToken nToken = INToken(reserveCache.xTokenAddress);\n require(\n nToken.getXTokenType() == XTokenType.NTokenUniswapV3,\n Errors.ONLY_UNIV3_ALLOWED\n );\n\n uint256[] memory tokenIds = new uint256[](1);\n tokenIds[0] = params.tokenId;\n ValidationLogic.validateWithdrawERC721(\n reservesData,\n reserveCache,\n params.asset,\n tokenIds\n );\n\n INTokenUniswapV3(reserveCache.xTokenAddress).decreaseUniswapV3Liquidity(\n params.user,\n params.tokenId,\n params.liquidityDecrease,\n params.amount0Min,\n params.amount1Min,\n params.receiveEthAsWeth\n );\n\n bool isUsedAsCollateral = ICollateralizableERC721(\n reserveCache.xTokenAddress\n ).isUsedAsCollateral(params.tokenId);\n if (isUsedAsCollateral) {\n if (userConfig.isBorrowingAny()) {\n ValidationLogic.validateHFAndLtvERC721(\n reservesData,\n reservesList,\n userConfig,\n params.asset,\n tokenIds,\n params.user,\n params.reservesCount,\n params.oracle\n );\n }\n }\n }\n\n /**\n * @notice Validates a transfer of PTokens. The sender is subjected to health factor validation to avoid\n * collateralization constraints violation.\n * @dev Emits the `ReserveUsedAsCollateralEnabled()` event for the `to` account, if the asset is being activated as\n * collateral.\n * @dev In case the `from` user transfers everything, `ReserveUsedAsCollateralDisabled()` is emitted for `from`.\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n * @param params The additional parameters needed to execute the finalizeTransfer function\n */\n function executeFinalizeTransferERC20(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n DataTypes.FinalizeTransferParams memory params\n ) external {\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n\n ValidationLogic.validateTransferERC20(reserve);\n\n uint256 reserveId = reserve.id;\n\n if (params.from != params.to && params.amount != 0) {\n DataTypes.UserConfigurationMap storage fromConfig = usersConfig[\n params.from\n ];\n\n if (fromConfig.isUsingAsCollateral(reserveId)) {\n if (fromConfig.isBorrowingAny()) {\n ValidationLogic.validateHFAndLtvERC20(\n reservesData,\n reservesList,\n usersConfig[params.from],\n params.asset,\n params.from,\n params.reservesCount,\n params.oracle\n );\n }\n\n if (params.balanceFromBefore == params.amount) {\n fromConfig.setUsingAsCollateral(reserveId, false);\n emit ReserveUsedAsCollateralDisabled(\n params.asset,\n params.from\n );\n }\n\n if (params.balanceToBefore == 0) {\n DataTypes.UserConfigurationMap\n storage toConfig = usersConfig[params.to];\n\n toConfig.setUsingAsCollateral(reserveId, true);\n emit ReserveUsedAsCollateralEnabled(\n params.asset,\n params.to\n );\n }\n }\n }\n }\n\n /**\n * @notice Validates a transfer of NTokens. The sender is subjected to health factor validation to avoid\n * collateralization constraints violation.\n * @dev In case the `from` user transfers everything, `ReserveUsedAsCollateralDisabled()` is emitted for `from`.\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param usersConfig The users configuration mapping that track the supplied/borrowed assets\n * @param params The additional parameters needed to execute the finalizeTransfer function\n */\n function executeFinalizeTransferERC721(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n mapping(address => DataTypes.UserConfigurationMap) storage usersConfig,\n DataTypes.FinalizeTransferERC721Params memory params\n ) external {\n DataTypes.ReserveData storage reserve = reservesData[params.asset];\n\n ValidationLogic.validateTransferERC721(\n reservesData,\n reserve,\n params.asset,\n params.tokenId\n );\n\n uint256 reserveId = reserve.id;\n\n if (params.from != params.to) {\n DataTypes.UserConfigurationMap storage fromConfig = usersConfig[\n params.from\n ];\n\n if (params.usedAsCollateral) {\n if (fromConfig.isBorrowingAny()) {\n uint256[] memory tokenIds = new uint256[](1);\n tokenIds[0] = params.tokenId;\n ValidationLogic.validateHFAndLtvERC721(\n reservesData,\n reservesList,\n usersConfig[params.from],\n params.asset,\n tokenIds,\n params.from,\n params.reservesCount,\n params.oracle\n );\n }\n\n if (params.balanceFromBefore == 1) {\n fromConfig.setUsingAsCollateral(reserveId, false);\n emit ReserveUsedAsCollateralDisabled(\n params.asset,\n params.from\n );\n }\n }\n }\n }\n\n /**\n * @notice Executes the 'set as collateral' feature. A user can choose to activate or deactivate an asset as\n * collateral at any point in time. Deactivating an asset as collateral is subjected to the usual health factor\n * checks to ensure collateralization.\n * @dev Emits the `ReserveUsedAsCollateralEnabled()` event if the asset can be activated as collateral.\n * @dev In case the asset is being deactivated as collateral, `ReserveUsedAsCollateralDisabled()` is emitted.\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param userConfig The users configuration mapping that track the supplied/borrowed assets\n * @param asset The address of the asset being configured as collateral\n * @param useAsCollateral True if the user wants to set the asset as collateral, false otherwise\n * @param reservesCount The number of initialized reserves\n * @param priceOracle The address of the price oracle\n */\n function executeUseERC20AsCollateral(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap storage userConfig,\n address asset,\n bool useAsCollateral,\n uint256 reservesCount,\n address priceOracle\n ) external {\n DataTypes.ReserveData storage reserve = reservesData[asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n uint256 userBalance = IERC20(reserveCache.xTokenAddress).balanceOf(\n msg.sender\n );\n\n ValidationLogic.validateSetUseERC20AsCollateral(\n reserveCache,\n userBalance\n );\n\n if (useAsCollateral == userConfig.isUsingAsCollateral(reserve.id))\n return;\n\n if (useAsCollateral) {\n userConfig.setUsingAsCollateral(reserve.id, true);\n emit ReserveUsedAsCollateralEnabled(asset, msg.sender);\n } else {\n userConfig.setUsingAsCollateral(reserve.id, false);\n ValidationLogic.validateHFAndLtvERC20(\n reservesData,\n reservesList,\n userConfig,\n asset,\n msg.sender,\n reservesCount,\n priceOracle\n );\n\n emit ReserveUsedAsCollateralDisabled(asset, msg.sender);\n }\n }\n\n /**\n * @notice Executes the 'set as collateral' feature. A user can choose to activate an asset as\n * collateral at any point in time.\n * @dev Emits the `ReserveUsedAsCollateralEnabled()` event if the asset can be activated as collateral.\n * @param reservesData The state of all the reserves\n * @param userConfig The users configuration mapping that track the supplied/borrowed assets\n * @param asset The address of the asset being configured as collateral\n * @param tokenIds The ids of the supplied ERC721 token\n * @param sender The address of NFT owner\n */\n function executeCollateralizeERC721(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.UserConfigurationMap storage userConfig,\n address asset,\n uint256[] calldata tokenIds,\n address sender\n ) external {\n DataTypes.ReserveData storage reserve = reservesData[asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n ValidationLogic.validateSetUseERC721AsCollateral(\n reservesData,\n reserveCache,\n asset,\n tokenIds\n );\n\n (\n uint256 oldCollateralizedBalance,\n uint256 newCollateralizedBalance\n ) = ICollateralizableERC721(reserveCache.xTokenAddress)\n .batchSetIsUsedAsCollateral(tokenIds, true, sender);\n\n if (oldCollateralizedBalance == 0 && newCollateralizedBalance != 0) {\n userConfig.setUsingAsCollateral(reserve.id, true);\n emit ReserveUsedAsCollateralEnabled(asset, sender);\n }\n }\n\n /**\n * @notice Executes the 'set as collateral' feature. A user can choose to deactivate an asset as\n * collateral at any point in time. Deactivating an asset as collateral is subjected to the usual health factor\n * checks to ensure collateralization.\n * @dev Emits the `ReserveUsedAsCollateralDisabled()` event if the asset can be deactivated as collateral.\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param userConfig The users configuration mapping that track the supplied/borrowed assets\n * @param asset The address of the asset being configured as collateral\n * @param tokenIds The ids of the supplied ERC721 token\n * @param sender The address of NFT owner\n * @param reservesCount The number of initialized reserves\n * @param priceOracle The address of the price oracle\n */\n function executeUncollateralizeERC721(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap storage userConfig,\n address asset,\n uint256[] calldata tokenIds,\n address sender,\n uint256 reservesCount,\n address priceOracle\n ) external {\n DataTypes.ReserveData storage reserve = reservesData[asset];\n DataTypes.ReserveCache memory reserveCache = reserve.cache();\n\n ValidationLogic.validateSetUseERC721AsCollateral(\n reservesData,\n reserveCache,\n asset,\n tokenIds\n );\n\n (\n uint256 oldCollateralizedBalance,\n uint256 newCollateralizedBalance\n ) = ICollateralizableERC721(reserveCache.xTokenAddress)\n .batchSetIsUsedAsCollateral(tokenIds, false, sender);\n\n if (oldCollateralizedBalance == newCollateralizedBalance) {\n return;\n }\n\n if (newCollateralizedBalance == 0) {\n userConfig.setUsingAsCollateral(reserve.id, false);\n emit ReserveUsedAsCollateralDisabled(asset, sender);\n }\n ValidationLogic.validateHFAndLtvERC721(\n reservesData,\n reservesList,\n userConfig,\n asset,\n tokenIds,\n sender,\n reservesCount,\n priceOracle\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/interfaces/IParaProxy.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.10;\n\n/******************************************************************************\\\n* EIP-2535: https://eips.ethereum.org/EIPS/eip-2535\n/******************************************************************************/\n\ninterface IParaProxy {\n enum ProxyImplementationAction {\n Add,\n Replace,\n Remove\n }\n // Add=0, Replace=1, Remove=2\n\n struct ProxyImplementation {\n address implAddress;\n ProxyImplementationAction action;\n bytes4[] functionSelectors;\n }\n\n /// @notice Add/replace/remove any number of functions and optionally execute\n /// a function with delegatecall\n /// @param _implementationParams Contains the implementation addresses and function selectors\n /// @param _init The address of the contract or implementation to execute _calldata\n /// @param _calldata A function call, including function selector and arguments\n /// _calldata is executed with delegatecall on _init\n function updateImplementation(\n ProxyImplementation[] calldata _implementationParams,\n address _init,\n bytes calldata _calldata\n ) external;\n\n event ImplementationUpdated(\n ProxyImplementation[] _implementationParams,\n address _init,\n bytes _calldata\n );\n}\n" }, "contracts/dependencies/seaport/contracts/lib/ConsiderationStructs.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.7;\n\nimport {\n OrderType,\n BasicOrderType,\n ItemType,\n Side\n} from \"./ConsiderationEnums.sol\";\n\n/**\n * @dev An order contains eleven components: an offerer, a zone (or account that\n * can cancel the order or restrict who can fulfill the order depending on\n * the type), the order type (specifying partial fill support as well as\n * restricted order status), the start and end time, a hash that will be\n * provided to the zone when validating restricted orders, a salt, a key\n * corresponding to a given conduit, a counter, and an arbitrary number of\n * offer items that can be spent along with consideration items that must\n * be received by their respective recipient.\n */\nstruct OrderComponents {\n address offerer;\n address zone;\n OfferItem[] offer;\n ConsiderationItem[] consideration;\n OrderType orderType;\n uint256 startTime;\n uint256 endTime;\n bytes32 zoneHash;\n uint256 salt;\n bytes32 conduitKey;\n uint256 counter;\n}\n\n/**\n * @dev An offer item has five components: an item type (ETH or other native\n * tokens, ERC20, ERC721, and ERC1155, as well as criteria-based ERC721 and\n * ERC1155), a token address, a dual-purpose \"identifierOrCriteria\"\n * component that will either represent a tokenId or a merkle root\n * depending on the item type, and a start and end amount that support\n * increasing or decreasing amounts over the duration of the respective\n * order.\n */\nstruct OfferItem {\n ItemType itemType;\n address token;\n uint256 identifierOrCriteria;\n uint256 startAmount;\n uint256 endAmount;\n}\n\n/**\n * @dev A consideration item has the same five components as an offer item and\n * an additional sixth component designating the required recipient of the\n * item.\n */\nstruct ConsiderationItem {\n ItemType itemType;\n address token;\n uint256 identifierOrCriteria;\n uint256 startAmount;\n uint256 endAmount;\n address payable recipient;\n}\n\n/**\n * @dev A spent item is translated from a utilized offer item and has four\n * components: an item type (ETH or other native tokens, ERC20, ERC721, and\n * ERC1155), a token address, a tokenId, and an amount.\n */\nstruct SpentItem {\n ItemType itemType;\n address token;\n uint256 identifier;\n uint256 amount;\n}\n\n/**\n * @dev A received item is translated from a utilized consideration item and has\n * the same four components as a spent item, as well as an additional fifth\n * component designating the required recipient of the item.\n */\nstruct ReceivedItem {\n ItemType itemType;\n address token;\n uint256 identifier;\n uint256 amount;\n address payable recipient;\n}\n\n/**\n * @dev For basic orders involving ETH / native / ERC20 <=> ERC721 / ERC1155\n * matching, a group of six functions may be called that only requires a\n * subset of the usual order arguments. Note the use of a \"basicOrderType\"\n * enum; this represents both the usual order type as well as the \"route\"\n * of the basic order (a simple derivation function for the basic order\n * type is `basicOrderType = orderType + (4 * basicOrderRoute)`.)\n */\nstruct BasicOrderParameters {\n // calldata offset\n address considerationToken; // 0x24\n uint256 considerationIdentifier; // 0x44\n uint256 considerationAmount; // 0x64\n address payable offerer; // 0x84\n address zone; // 0xa4\n address offerToken; // 0xc4\n uint256 offerIdentifier; // 0xe4\n uint256 offerAmount; // 0x104\n BasicOrderType basicOrderType; // 0x124\n uint256 startTime; // 0x144\n uint256 endTime; // 0x164\n bytes32 zoneHash; // 0x184\n uint256 salt; // 0x1a4\n bytes32 offererConduitKey; // 0x1c4\n bytes32 fulfillerConduitKey; // 0x1e4\n uint256 totalOriginalAdditionalRecipients; // 0x204\n AdditionalRecipient[] additionalRecipients; // 0x224\n bytes signature; // 0x244\n // Total length, excluding dynamic array data: 0x264 (580)\n}\n\n/**\n * @dev Basic orders can supply any number of additional recipients, with the\n * implied assumption that they are supplied from the offered ETH (or other\n * native token) or ERC20 token for the order.\n */\nstruct AdditionalRecipient {\n uint256 amount;\n address payable recipient;\n}\n\n/**\n * @dev The full set of order components, with the exception of the counter,\n * must be supplied when fulfilling more sophisticated orders or groups of\n * orders. The total number of original consideration items must also be\n * supplied, as the caller may specify additional consideration items.\n */\nstruct OrderParameters {\n address offerer; // 0x00\n address zone; // 0x20\n OfferItem[] offer; // 0x40\n ConsiderationItem[] consideration; // 0x60\n OrderType orderType; // 0x80\n uint256 startTime; // 0xa0\n uint256 endTime; // 0xc0\n bytes32 zoneHash; // 0xe0\n uint256 salt; // 0x100\n bytes32 conduitKey; // 0x120\n uint256 totalOriginalConsiderationItems; // 0x140\n // offer.length // 0x160\n}\n\n/**\n * @dev Orders require a signature in addition to the other order parameters.\n */\nstruct Order {\n OrderParameters parameters;\n bytes signature;\n}\n\n/**\n * @dev Advanced orders include a numerator (i.e. a fraction to attempt to fill)\n * and a denominator (the total size of the order) in addition to the\n * signature and other order parameters. It also supports an optional field\n * for supplying extra data; this data will be included in a staticcall to\n * `isValidOrderIncludingExtraData` on the zone for the order if the order\n * type is restricted and the offerer or zone are not the caller.\n */\nstruct AdvancedOrder {\n OrderParameters parameters;\n uint120 numerator;\n uint120 denominator;\n bytes signature;\n bytes extraData;\n}\n\n/**\n * @dev Orders can be validated (either explicitly via `validate`, or as a\n * consequence of a full or partial fill), specifically cancelled (they can\n * also be cancelled in bulk via incrementing a per-zone counter), and\n * partially or fully filled (with the fraction filled represented by a\n * numerator and denominator).\n */\nstruct OrderStatus {\n bool isValidated;\n bool isCancelled;\n uint120 numerator;\n uint120 denominator;\n}\n\n/**\n * @dev A criteria resolver specifies an order, side (offer vs. consideration),\n * and item index. It then provides a chosen identifier (i.e. tokenId)\n * alongside a merkle proof demonstrating the identifier meets the required\n * criteria.\n */\nstruct CriteriaResolver {\n uint256 orderIndex;\n Side side;\n uint256 index;\n uint256 identifier;\n bytes32[] criteriaProof;\n}\n\n/**\n * @dev A fulfillment is applied to a group of orders. It decrements a series of\n * offer and consideration items, then generates a single execution\n * element. A given fulfillment can be applied to as many offer and\n * consideration items as desired, but must contain at least one offer and\n * at least one consideration that match. The fulfillment must also remain\n * consistent on all key parameters across all offer items (same offerer,\n * token, type, tokenId, and conduit preference) as well as across all\n * consideration items (token, type, tokenId, and recipient).\n */\nstruct Fulfillment {\n FulfillmentComponent[] offerComponents;\n FulfillmentComponent[] considerationComponents;\n}\n\n/**\n * @dev Each fulfillment component contains one index referencing a specific\n * order and another referencing a specific offer or consideration item.\n */\nstruct FulfillmentComponent {\n uint256 orderIndex;\n uint256 itemIndex;\n}\n\n/**\n * @dev An execution is triggered once all consideration items have been zeroed\n * out. It sends the item in question from the offerer to the item's\n * recipient, optionally sourcing approvals from either this contract\n * directly or from the offerer's chosen conduit if one is specified. An\n * execution is not provided as an argument, but rather is derived via\n * orders, criteria resolvers, and fulfillments (where the total number of\n * executions will be less than or equal to the total number of indicated\n * fulfillments) and returned as part of `matchOrders`.\n */\nstruct Execution {\n ReceivedItem item;\n address offerer;\n bytes32 conduitKey;\n}\n" }, "contracts/dependencies/seaport/contracts/lib/ConsiderationEnums.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.7;\n\n// prettier-ignore\nenum OrderType {\n // 0: no partial fills, anyone can execute\n FULL_OPEN,\n\n // 1: partial fills supported, anyone can execute\n PARTIAL_OPEN,\n\n // 2: no partial fills, only offerer or zone can execute\n FULL_RESTRICTED,\n\n // 3: partial fills supported, only offerer or zone can execute\n PARTIAL_RESTRICTED\n}\n\n// prettier-ignore\nenum BasicOrderType {\n // 0: no partial fills, anyone can execute\n ETH_TO_ERC721_FULL_OPEN,\n\n // 1: partial fills supported, anyone can execute\n ETH_TO_ERC721_PARTIAL_OPEN,\n\n // 2: no partial fills, only offerer or zone can execute\n ETH_TO_ERC721_FULL_RESTRICTED,\n\n // 3: partial fills supported, only offerer or zone can execute\n ETH_TO_ERC721_PARTIAL_RESTRICTED,\n\n // 4: no partial fills, anyone can execute\n ETH_TO_ERC1155_FULL_OPEN,\n\n // 5: partial fills supported, anyone can execute\n ETH_TO_ERC1155_PARTIAL_OPEN,\n\n // 6: no partial fills, only offerer or zone can execute\n ETH_TO_ERC1155_FULL_RESTRICTED,\n\n // 7: partial fills supported, only offerer or zone can execute\n ETH_TO_ERC1155_PARTIAL_RESTRICTED,\n\n // 8: no partial fills, anyone can execute\n ERC20_TO_ERC721_FULL_OPEN,\n\n // 9: partial fills supported, anyone can execute\n ERC20_TO_ERC721_PARTIAL_OPEN,\n\n // 10: no partial fills, only offerer or zone can execute\n ERC20_TO_ERC721_FULL_RESTRICTED,\n\n // 11: partial fills supported, only offerer or zone can execute\n ERC20_TO_ERC721_PARTIAL_RESTRICTED,\n\n // 12: no partial fills, anyone can execute\n ERC20_TO_ERC1155_FULL_OPEN,\n\n // 13: partial fills supported, anyone can execute\n ERC20_TO_ERC1155_PARTIAL_OPEN,\n\n // 14: no partial fills, only offerer or zone can execute\n ERC20_TO_ERC1155_FULL_RESTRICTED,\n\n // 15: partial fills supported, only offerer or zone can execute\n ERC20_TO_ERC1155_PARTIAL_RESTRICTED,\n\n // 16: no partial fills, anyone can execute\n ERC721_TO_ERC20_FULL_OPEN,\n\n // 17: partial fills supported, anyone can execute\n ERC721_TO_ERC20_PARTIAL_OPEN,\n\n // 18: no partial fills, only offerer or zone can execute\n ERC721_TO_ERC20_FULL_RESTRICTED,\n\n // 19: partial fills supported, only offerer or zone can execute\n ERC721_TO_ERC20_PARTIAL_RESTRICTED,\n\n // 20: no partial fills, anyone can execute\n ERC1155_TO_ERC20_FULL_OPEN,\n\n // 21: partial fills supported, anyone can execute\n ERC1155_TO_ERC20_PARTIAL_OPEN,\n\n // 22: no partial fills, only offerer or zone can execute\n ERC1155_TO_ERC20_FULL_RESTRICTED,\n\n // 23: partial fills supported, only offerer or zone can execute\n ERC1155_TO_ERC20_PARTIAL_RESTRICTED\n}\n\n// prettier-ignore\nenum BasicOrderRouteType {\n // 0: provide Ether (or other native token) to receive offered ERC721 item.\n ETH_TO_ERC721,\n\n // 1: provide Ether (or other native token) to receive offered ERC1155 item.\n ETH_TO_ERC1155,\n\n // 2: provide ERC20 item to receive offered ERC721 item.\n ERC20_TO_ERC721,\n\n // 3: provide ERC20 item to receive offered ERC1155 item.\n ERC20_TO_ERC1155,\n\n // 4: provide ERC721 item to receive offered ERC20 item.\n ERC721_TO_ERC20,\n\n // 5: provide ERC1155 item to receive offered ERC20 item.\n ERC1155_TO_ERC20\n}\n\n// prettier-ignore\nenum ItemType {\n // 0: ETH on mainnet, MATIC on polygon, etc.\n NATIVE,\n\n // 1: ERC20 items (ERC777 and ERC20 analogues could also technically work)\n ERC20,\n\n // 2: ERC721 items\n ERC721,\n\n // 3: ERC1155 items\n ERC1155,\n\n // 4: ERC721 items where a number of tokenIds are supported\n ERC721_WITH_CRITERIA,\n\n // 5: ERC1155 items where a number of ids are supported\n ERC1155_WITH_CRITERIA\n}\n\n// prettier-ignore\nenum Side {\n // 0: Items that can be spent\n OFFER,\n\n // 1: Items that must be received\n CONSIDERATION\n}\n" }, "contracts/interfaces/IInitializableNToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IRewardController} from \"./IRewardController.sol\";\nimport {IPool} from \"./IPool.sol\";\n\n/**\n * @title IInitializablenToken\n *\n * @notice Interface for the initialize function on NToken\n **/\ninterface IInitializableNToken {\n /**\n * @dev Emitted when an nToken is initialized\n * @param underlyingAsset The address of the underlying asset\n * @param pool The address of the associated pool\n * @param incentivesController The address of the incentives controller for this nToken\n * @param nTokenName The name of the nToken\n * @param nTokenSymbol The symbol of the nToken\n * @param params A set of encoded parameters for additional initialization\n **/\n event Initialized(\n address indexed underlyingAsset,\n address indexed pool,\n address incentivesController,\n string nTokenName,\n string nTokenSymbol,\n bytes params\n );\n\n /**\n * @notice Initializes the nToken\n * @param pool The pool contract that is initializing this contract\n * @param underlyingAsset The address of the underlying asset of this nToken (E.g. WETH for pWETH)\n * @param incentivesController The smart contract managing potential incentives distribution\n * @param nTokenName The name of the nToken\n * @param nTokenSymbol The symbol of the nToken\n * @param params A set of encoded parameters for additional initialization\n */\n function initialize(\n IPool pool,\n address underlyingAsset,\n IRewardController incentivesController,\n string calldata nTokenName,\n string calldata nTokenSymbol,\n bytes calldata params\n ) external;\n}\n" }, "contracts/interfaces/IXTokenType.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title IXTokenType\n * @author ParallelFi\n * @notice Defines the basic interface for an IXTokenType.\n **/\nenum XTokenType {\n PhantomData, // unused\n NToken,\n NTokenMoonBirds,\n NTokenUniswapV3,\n NTokenBAYC,\n NTokenMAYC,\n PToken,\n DelegationAwarePToken,\n RebasingPToken,\n PTokenAToken,\n PTokenStETH,\n PTokenSApe\n}\n\ninterface IXTokenType {\n /**\n * @notice return token type`of xToken\n **/\n function getXTokenType() external pure returns (XTokenType);\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/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/IERC1155Receiver.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.10;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n" }, "contracts/interfaces/IRewardController.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title IRewardController\n *\n * @notice Defines the basic interface for an ParaSpace Incentives Controller.\n **/\ninterface IRewardController {\n /**\n * @dev Emitted during `handleAction`, `claimRewards` and `claimRewardsOnBehalf`\n * @param user The user that accrued rewards\n * @param amount The amount of accrued rewards\n */\n event RewardsAccrued(address indexed user, uint256 amount);\n\n event RewardsClaimed(\n address indexed user,\n address indexed to,\n uint256 amount\n );\n\n /**\n * @dev Emitted during `claimRewards` and `claimRewardsOnBehalf`\n * @param user The address that accrued rewards\n * @param to The address that will be receiving the rewards\n * @param claimer The address that performed the claim\n * @param amount The amount of rewards\n */\n event RewardsClaimed(\n address indexed user,\n address indexed to,\n address indexed claimer,\n uint256 amount\n );\n\n /**\n * @dev Emitted during `setClaimer`\n * @param user The address of the user\n * @param claimer The address of the claimer\n */\n event ClaimerSet(address indexed user, address indexed claimer);\n\n /**\n * @notice Returns the configuration of the distribution for a certain asset\n * @param asset The address of the reference asset of the distribution\n * @return The asset index\n * @return The emission per second\n * @return The last updated timestamp\n **/\n function getAssetData(address asset)\n external\n view\n returns (\n uint256,\n uint256,\n uint256\n );\n\n /**\n * LEGACY **************************\n * @dev Returns the configuration of the distribution for a certain asset\n * @param asset The address of the reference asset of the distribution\n * @return The asset index, the emission per second and the last updated timestamp\n **/\n function assets(address asset)\n external\n view\n returns (\n uint128,\n uint128,\n uint256\n );\n\n /**\n * @notice Whitelists an address to claim the rewards on behalf of another address\n * @param user The address of the user\n * @param claimer The address of the claimer\n */\n function setClaimer(address user, address claimer) external;\n\n /**\n * @notice Returns the whitelisted claimer for a certain address (0x0 if not set)\n * @param user The address of the user\n * @return The claimer address\n */\n function getClaimer(address user) external view returns (address);\n\n /**\n * @notice Configure assets for a certain rewards emission\n * @param assets The assets to incentivize\n * @param emissionsPerSecond The emission for each asset\n */\n function configureAssets(\n address[] calldata assets,\n uint256[] calldata emissionsPerSecond\n ) external;\n\n /**\n * @notice Called by the corresponding asset on any update that affects the rewards distribution\n * @param asset The address of the user\n * @param userBalance The balance of the user of the asset in the pool\n * @param totalSupply The total supply of the asset in the pool\n **/\n function handleAction(\n address asset,\n uint256 totalSupply,\n uint256 userBalance\n ) external;\n\n /**\n * @notice Returns the total of rewards of a user, already accrued + not yet accrued\n * @param assets The assets to accumulate rewards for\n * @param user The address of the user\n * @return The rewards\n **/\n function getRewardsBalance(address[] calldata assets, address user)\n external\n view\n returns (uint256);\n\n /**\n * @notice Claims reward for a user, on the assets of the pool, accumulating the pending rewards\n * @param assets The assets to accumulate rewards for\n * @param amount Amount of rewards to claim\n * @param to Address that will be receiving the rewards\n * @return Rewards claimed\n **/\n function claimRewards(\n address[] calldata assets,\n uint256 amount,\n address to\n ) external returns (uint256);\n\n /**\n * @notice Claims reward for a user on its behalf, on the assets of the pool, accumulating the pending rewards.\n * @dev The caller must be whitelisted via \"allowClaimOnBehalf\" function by the RewardsAdmin role manager\n * @param assets The assets to accumulate rewards for\n * @param amount The amount of rewards to claim\n * @param user The address to check and claim rewards\n * @param to The address that will be receiving the rewards\n * @return The amount of rewards claimed\n **/\n function claimRewardsOnBehalf(\n address[] calldata assets,\n uint256 amount,\n address user,\n address to\n ) external returns (uint256);\n\n /**\n * @notice Returns the unclaimed rewards of the user\n * @param user The address of the user\n * @return The unclaimed user rewards\n */\n function getUserUnclaimedRewards(address user)\n external\n view\n returns (uint256);\n\n /**\n * @notice Returns the user index for a specific asset\n * @param user The address of the user\n * @param asset The asset to incentivize\n * @return The user index for the asset\n */\n function getUserAssetData(address user, address asset)\n external\n view\n returns (uint256);\n\n /**\n * @notice for backward compatibility with previous implementation of the Incentives controller\n * @return The address of the reward token\n */\n function REWARD_TOKEN() external view returns (address);\n\n /**\n * @notice for backward compatibility with previous implementation of the Incentives controller\n * @return The precision used in the incentives controller\n */\n function PRECISION() external view returns (uint8);\n\n /**\n * @dev Gets the distribution end timestamp of the emissions\n */\n function DISTRIBUTION_END() external view returns (uint256);\n}\n" }, "contracts/interfaces/IPool.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolCore} from \"./IPoolCore.sol\";\nimport {IPoolMarketplace} from \"./IPoolMarketplace.sol\";\nimport {IPoolParameters} from \"./IPoolParameters.sol\";\nimport \"./IPoolApeStaking.sol\";\n\n/**\n * @title IPool\n *\n * @notice Defines the basic interface for an ParaSpace Pool.\n **/\ninterface IPool is\n IPoolCore,\n IPoolMarketplace,\n IPoolParameters,\n IPoolApeStaking\n{\n\n}\n" }, "contracts/interfaces/IPoolMarketplace.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolAddressesProvider} from \"./IPoolAddressesProvider.sol\";\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\n\n/**\n * @title IPool\n *\n * @notice Defines the basic interface for an ParaSpace Pool.\n **/\ninterface IPoolMarketplace {\n event BuyWithCredit(\n bytes32 indexed marketplaceId,\n DataTypes.OrderInfo orderInfo,\n DataTypes.Credit credit\n );\n\n event AcceptBidWithCredit(\n bytes32 indexed marketplaceId,\n DataTypes.OrderInfo orderInfo,\n DataTypes.Credit credit\n );\n\n /**\n * @notice Implements the buyWithCredit feature. BuyWithCredit allows users to buy NFT from various NFT marketplaces\n * including OpenSea, LooksRare, X2Y2 etc. Users can use NFT's credit and will need to pay at most (1 - LTV) * $NFT\n * @dev\n * @param marketplaceId The marketplace identifier\n * @param payload The encoded parameters to be passed to marketplace contract (selector eliminated)\n * @param credit The credit that user would like to use for this purchase\n * @param referralCode The referral code used\n */\n function buyWithCredit(\n bytes32 marketplaceId,\n bytes calldata payload,\n DataTypes.Credit calldata credit,\n uint16 referralCode\n ) external payable;\n\n /**\n * @notice Implements the batchBuyWithCredit feature. BuyWithCredit allows users to buy NFT from various NFT marketplaces\n * including OpenSea, LooksRare, X2Y2 etc. Users can use NFT's credit and will need to pay at most (1 - LTV) * $NFT\n * @dev marketplaceIds[i] should match payload[i] and credits[i]\n * @param marketplaceIds The marketplace identifiers\n * @param payloads The encoded parameters to be passed to marketplace contract (selector eliminated)\n * @param credits The credits that user would like to use for this purchase\n * @param referralCode The referral code used\n */\n function batchBuyWithCredit(\n bytes32[] calldata marketplaceIds,\n bytes[] calldata payloads,\n DataTypes.Credit[] calldata credits,\n uint16 referralCode\n ) external payable;\n\n /**\n * @notice Implements the acceptBidWithCredit feature. AcceptBidWithCredit allows users to\n * accept a leveraged bid on ParaSpace NFT marketplace. Users can submit leveraged bid and pay\n * at most (1 - LTV) * $NFT\n * @dev The nft receiver just needs to do the downpayment\n * @param marketplaceId The marketplace identifier\n * @param payload The encoded parameters to be passed to marketplace contract (selector eliminated)\n * @param credit The credit that user would like to use for this purchase\n * @param onBehalfOf Address of the user who will sell the NFT\n * @param referralCode The referral code used\n */\n function acceptBidWithCredit(\n bytes32 marketplaceId,\n bytes calldata payload,\n DataTypes.Credit calldata credit,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Implements the batchAcceptBidWithCredit feature. AcceptBidWithCredit allows users to\n * accept a leveraged bid on ParaSpace NFT marketplace. Users can submit leveraged bid and pay\n * at most (1 - LTV) * $NFT\n * @dev The nft receiver just needs to do the downpayment\n * @param marketplaceIds The marketplace identifiers\n * @param payloads The encoded parameters to be passed to marketplace contract (selector eliminated)\n * @param credits The credits that the makers have approved to use for this purchase\n * @param onBehalfOf Address of the user who will sell the NFTs\n * @param referralCode The referral code used\n */\n function batchAcceptBidWithCredit(\n bytes32[] calldata marketplaceIds,\n bytes[] calldata payloads,\n DataTypes.Credit[] calldata credits,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n}\n" }, "contracts/interfaces/IPoolParameters.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolAddressesProvider} from \"./IPoolAddressesProvider.sol\";\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\n\n/**\n * @title IPool\n *\n * @notice Defines the basic interface for an ParaSpace Pool.\n **/\ninterface IPoolParameters {\n /**\n * @dev Emitted when the state of a reserve is updated.\n * @param reserve The address of the underlying asset of the reserve\n * @param liquidityRate The next liquidity rate\n * @param variableBorrowRate The next variable borrow rate\n * @param liquidityIndex The next liquidity index\n * @param variableBorrowIndex The next variable borrow index\n **/\n event ReserveDataUpdated(\n address indexed reserve,\n uint256 liquidityRate,\n uint256 variableBorrowRate,\n uint256 liquidityIndex,\n uint256 variableBorrowIndex\n );\n\n /**\n * @notice Initializes a reserve, activating it, assigning an xToken and debt tokens and an\n * interest rate strategy\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param xTokenAddress The address of the xToken that will be assigned to the reserve\n * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve\n * @param interestRateStrategyAddress The address of the interest rate strategy contract\n **/\n function initReserve(\n address asset,\n address xTokenAddress,\n address variableDebtAddress,\n address interestRateStrategyAddress,\n address auctionStrategyAddress\n ) external;\n\n /**\n * @notice Drop a reserve\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n **/\n function dropReserve(address asset) external;\n\n /**\n * @notice Updates the address of the interest rate strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param rateStrategyAddress The address of the interest rate strategy contract\n **/\n function setReserveInterestRateStrategyAddress(\n address asset,\n address rateStrategyAddress\n ) external;\n\n /**\n * @notice Updates the address of the auction strategy contract\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param auctionStrategyAddress The address of the auction strategy contract\n **/\n function setReserveAuctionStrategyAddress(\n address asset,\n address auctionStrategyAddress\n ) external;\n\n /**\n * @notice Sets the configuration bitmap of the reserve as a whole\n * @dev Only callable by the PoolConfigurator contract\n * @param asset The address of the underlying asset of the reserve\n * @param configuration The new configuration bitmap\n **/\n function setConfiguration(\n address asset,\n DataTypes.ReserveConfigurationMap calldata configuration\n ) external;\n\n /**\n * @notice Mints the assets accrued through the reserve factor to the treasury in the form of xTokens\n * @param assets The list of reserves for which the minting needs to be executed\n **/\n function mintToTreasury(address[] calldata assets) external;\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param assetType The asset type of the token\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amountOrTokenId The amount or id of token to transfer\n */\n function rescueTokens(\n DataTypes.AssetType assetType,\n address token,\n address to,\n uint256 amountOrTokenId\n ) external;\n\n /**\n * @notice Set the auction recovery health factor\n * @param value The new auction health factor\n */\n function setAuctionRecoveryHealthFactor(uint64 value) external;\n\n /**\n * @notice Set auction validity time, all auctions triggered before the validity time will be considered as invalid\n * @param user The user address\n */\n function setAuctionValidityTime(address user) external;\n\n /**\n * @notice Returns the user account data across all the reserves\n * @param user The address of the user\n * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed\n * @return totalDebtBase The total debt of the user in the base currency used by the price feed\n * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed\n * @return currentLiquidationThreshold The liquidation threshold of the user\n * @return ltv The loan to value of The user\n * @return healthFactor The current health factor of the user\n **/\n function getUserAccountData(address user)\n external\n view\n returns (\n uint256 totalCollateralBase,\n uint256 totalDebtBase,\n uint256 availableBorrowsBase,\n uint256 currentLiquidationThreshold,\n uint256 ltv,\n uint256 healthFactor,\n uint256 erc721HealthFactor\n );\n\n /**\n * @notice Returns Ltv and Liquidation Threshold for the asset\n * @param asset The address of the asset\n * @param tokenId The tokenId of the asset\n * @return ltv The loan to value of the asset\n * @return lt The liquidation threshold value of the asset\n **/\n function getAssetLtvAndLT(address asset, uint256 tokenId)\n external\n view\n returns (uint256 ltv, uint256 lt);\n}\n" }, "contracts/interfaces/IPoolApeStaking.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport \"../dependencies/yoga-labs/ApeCoinStaking.sol\";\n\n/**\n * @title IPoolApeStaking\n *\n * @notice Defines the basic interface for an ParaSpace Ape Staking Pool.\n **/\ninterface IPoolApeStaking {\n struct StakingInfo {\n // Contract address of BAYC/MAYC\n address nftAsset;\n // Borrow amount of Ape from lending pool\n uint256 borrowAmount;\n // Cash amount of Ape from user wallet\n uint256 cashAmount;\n }\n\n /**\n * @notice Deposit ape coin to BAYC/MAYC pool or BAKC pool\n * @param stakingInfo Detail info of the staking\n * @param _nfts Array of BAYC/MAYC NFT's with staked amounts\n * @param _nftPairs Array of Paired BAYC/MAYC NFT's with staked amounts\n * @dev Need check User health factor > 1.\n */\n function borrowApeAndStake(\n StakingInfo calldata stakingInfo,\n ApeCoinStaking.SingleNft[] calldata _nfts,\n ApeCoinStaking.PairNftDepositWithAmount[] calldata _nftPairs\n ) external;\n\n /**\n * @notice Withdraw staked ApeCoin from the BAYC/MAYC pool\n * @param nftAsset Contract address of BAYC/MAYC\n * @param _nfts Array of BAYC/MAYC NFT's with staked amounts\n * @dev Need check User health factor > 1.\n */\n function withdrawApeCoin(\n address nftAsset,\n ApeCoinStaking.SingleNft[] calldata _nfts\n ) external;\n\n /**\n * @notice Claim rewards for array of tokenIds from the BAYC/MAYC pool\n * @param nftAsset Contract address of BAYC/MAYC\n * @param _nfts Array of NFTs owned and committed by the msg.sender\n * @dev Need check User health factor > 1.\n */\n function claimApeCoin(address nftAsset, uint256[] calldata _nfts) external;\n\n /**\n * @notice Withdraw staked ApeCoin from the BAKC pool\n * @param nftAsset Contract address of BAYC/MAYC\n * @param _nftPairs Array of Paired BAYC/MAYC NFT's with staked amounts\n * @dev Need check User health factor > 1.\n */\n function withdrawBAKC(\n address nftAsset,\n ApeCoinStaking.PairNftWithdrawWithAmount[] memory _nftPairs\n ) external;\n\n /**\n * @notice Claim rewards for array of tokenIds from the BAYC/MAYC pool\n * @param nftAsset Contract address of BAYC/MAYC\n * @param _nftPairs Array of Paired BAYC/MAYC NFT's\n * @dev Need check User health factor > 1.\n */\n function claimBAKC(\n address nftAsset,\n ApeCoinStaking.PairNft[] calldata _nftPairs\n ) external;\n\n /**\n * @notice Unstake user Ape coin staking position and repay user debt\n * @param nftAsset Contract address of BAYC/MAYC\n * @param tokenId Token id of the ape staking position on\n * @dev Need check User health factor > 1.\n */\n function unstakeApePositionAndRepay(address nftAsset, uint256 tokenId)\n external;\n\n /**\n * @notice repay asset and supply asset for user\n * @param underlyingAsset Contract address of BAYC/MAYC\n * @param repayAsset Asset address to repay and supply\n * @param onBehalfOf The beneficiary of the repay and supply\n * @dev Convenient callback function for unstakeApePositionAndRepay. Only NToken of BAYC/MAYC can call this.\n */\n function repayAndSupply(\n address underlyingAsset,\n address repayAsset,\n address onBehalfOf,\n uint256 repayAmount,\n uint256 supplyAmount\n ) 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/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/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/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/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/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/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/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" }, "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/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/IERC1271.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)\n\npragma solidity 0.8.10;\n\n/**\n * @dev Interface of the ERC1271 standard signature validation method for\n * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].\n *\n * _Available since v4.1._\n */\ninterface IERC1271 {\n /**\n * @dev Should return whether the signature provided is valid for the provided data\n * @param hash Hash of the data to be signed\n * @param signature Signature byte array associated with _data\n */\n function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);\n}" }, "contracts/dependencies/looksrare/contracts/libraries/OrderTypes.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title OrderTypes\n * @notice This library contains order types for the LooksRare exchange.\n */\nlibrary OrderTypes {\n // keccak256(\"MakerOrder(bool isOrderAsk,address signer,address collection,uint256 price,uint256 tokenId,uint256 amount,address strategy,address currency,uint256 nonce,uint256 startTime,uint256 endTime,uint256 minPercentageToAsk,bytes params)\")\n bytes32 internal constant MAKER_ORDER_HASH = 0x40261ade532fa1d2c7293df30aaadb9b3c616fae525a0b56d3d411c841a85028;\n\n struct MakerOrder {\n bool isOrderAsk; // true --> ask / false --> bid\n address signer; // signer of the maker order\n address collection; // collection address\n uint256 price; // price (used as )\n uint256 tokenId; // id of the token\n uint256 amount; // amount of tokens to sell/purchase (must be 1 for ERC721, 1+ for ERC1155)\n address strategy; // strategy for trade execution (e.g., DutchAuction, StandardSaleForFixedPrice)\n address currency; // currency (e.g., WETH)\n uint256 nonce; // order nonce (must be unique unless new maker order is meant to override existing one e.g., lower ask price)\n uint256 startTime; // startTime in timestamp\n uint256 endTime; // endTime in timestamp\n uint256 minPercentageToAsk; // slippage protection (9000 --> 90% of the final price must return to ask)\n bytes params; // additional parameters\n uint8 v; // v: parameter (27 or 28)\n bytes32 r; // r: parameter\n bytes32 s; // s: parameter\n }\n\n struct TakerOrder {\n bool isOrderAsk; // true --> ask / false --> bid\n address taker; // msg.sender\n uint256 price; // final price for the purchase\n uint256 tokenId;\n uint256 minPercentageToAsk; // // slippage protection (9000 --> 90% of the final price must return to ask)\n bytes params; // other params (e.g., tokenId)\n }\n\n function hash(MakerOrder memory makerOrder) internal pure returns (bytes32) {\n return\n keccak256(\n abi.encode(\n MAKER_ORDER_HASH,\n makerOrder.isOrderAsk,\n makerOrder.signer,\n makerOrder.collection,\n makerOrder.price,\n makerOrder.tokenId,\n makerOrder.amount,\n makerOrder.strategy,\n makerOrder.currency,\n makerOrder.nonce,\n makerOrder.startTime,\n makerOrder.endTime,\n makerOrder.minPercentageToAsk,\n keccak256(makerOrder.params)\n )\n );\n }\n}\n" }, "contracts/dependencies/seaport/contracts/interfaces/SeaportInterface.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.7;\n\nimport {\n BasicOrderParameters,\n OrderComponents,\n Fulfillment,\n FulfillmentComponent,\n Execution,\n Order,\n AdvancedOrder,\n OrderStatus,\n CriteriaResolver\n} from \"../lib/ConsiderationStructs.sol\";\n\n/**\n * @title SeaportInterface\n * @author 0age\n * @custom:version 1.1\n * @notice Seaport is a generalized ETH/ERC20/ERC721/ERC1155 marketplace. It\n * minimizes external calls to the greatest extent possible and provides\n * lightweight methods for common routes as well as more flexible\n * methods for composing advanced orders.\n *\n * @dev SeaportInterface contains all external function interfaces for Seaport.\n */\ninterface SeaportInterface {\n /**\n * @notice Fulfill an order offering an ERC721 token by supplying Ether (or\n * the native token for the given chain) as consideration for the\n * order. An arbitrary number of \"additional recipients\" may also be\n * supplied which will each receive native tokens from the fulfiller\n * as consideration.\n *\n * @param parameters Additional information on the fulfilled order. Note\n * that the offerer must first approve this contract (or\n * their preferred conduit if indicated by the order) for\n * their offered ERC721 token to be transferred.\n *\n * @return fulfilled A boolean indicating whether the order has been\n * successfully fulfilled.\n */\n function fulfillBasicOrder(BasicOrderParameters calldata parameters)\n external\n payable\n returns (bool fulfilled);\n\n /**\n * @notice Fulfill an order with an arbitrary number of items for offer and\n * consideration. Note that this function does not support\n * criteria-based orders or partial filling of orders (though\n * filling the remainder of a partially-filled order is supported).\n *\n * @param order The order to fulfill. Note that both the\n * offerer and the fulfiller must first approve\n * this contract (or the corresponding conduit if\n * indicated) to transfer any relevant tokens on\n * their behalf and that contracts must implement\n * `onERC1155Received` to receive ERC1155 tokens\n * as consideration.\n * @param fulfillerConduitKey A bytes32 value indicating what conduit, if\n * any, to source the fulfiller's token approvals\n * from. The zero hash signifies that no conduit\n * should be used, with direct approvals set on\n * Seaport.\n *\n * @return fulfilled A boolean indicating whether the order has been\n * successfully fulfilled.\n */\n function fulfillOrder(Order calldata order, bytes32 fulfillerConduitKey)\n external\n payable\n returns (bool fulfilled);\n\n /**\n * @notice Fill an order, fully or partially, with an arbitrary number of\n * items for offer and consideration alongside criteria resolvers\n * containing specific token identifiers and associated proofs.\n *\n * @param advancedOrder The order to fulfill along with the fraction\n * of the order to attempt to fill. Note that\n * both the offerer and the fulfiller must first\n * approve this contract (or their preferred\n * conduit if indicated by the order) to transfer\n * any relevant tokens on their behalf and that\n * contracts must implement `onERC1155Received`\n * to receive ERC1155 tokens as consideration.\n * Also note that all offer and consideration\n * components must have no remainder after\n * multiplication of the respective amount with\n * the supplied fraction for the partial fill to\n * be considered valid.\n * @param criteriaResolvers An array where each element contains a\n * reference to a specific offer or\n * consideration, a token identifier, and a proof\n * that the supplied token identifier is\n * contained in the merkle root held by the item\n * in question's criteria element. Note that an\n * empty criteria indicates that any\n * (transferable) token identifier on the token\n * in question is valid and that no associated\n * proof needs to be supplied.\n * @param fulfillerConduitKey A bytes32 value indicating what conduit, if\n * any, to source the fulfiller's token approvals\n * from. The zero hash signifies that no conduit\n * should be used, with direct approvals set on\n * Seaport.\n * @param recipient The intended recipient for all received items,\n * with `address(0)` indicating that the caller\n * should receive the items.\n *\n * @return fulfilled A boolean indicating whether the order has been\n * successfully fulfilled.\n */\n function fulfillAdvancedOrder(\n AdvancedOrder calldata advancedOrder,\n CriteriaResolver[] calldata criteriaResolvers,\n bytes32 fulfillerConduitKey,\n address recipient\n ) external payable returns (bool fulfilled);\n\n /**\n * @notice Attempt to fill a group of orders, each with an arbitrary number\n * of items for offer and consideration. Any order that is not\n * currently active, has already been fully filled, or has been\n * cancelled will be omitted. Remaining offer and consideration\n * items will then be aggregated where possible as indicated by the\n * supplied offer and consideration component arrays and aggregated\n * items will be transferred to the fulfiller or to each intended\n * recipient, respectively. Note that a failing item transfer or an\n * issue with order formatting will cause the entire batch to fail.\n * Note that this function does not support criteria-based orders or\n * partial filling of orders (though filling the remainder of a\n * partially-filled order is supported).\n *\n * @param orders The orders to fulfill. Note that both\n * the offerer and the fulfiller must first\n * approve this contract (or the\n * corresponding conduit if indicated) to\n * transfer any relevant tokens on their\n * behalf and that contracts must implement\n * `onERC1155Received` to receive ERC1155\n * tokens as consideration.\n * @param offerFulfillments An array of FulfillmentComponent arrays\n * indicating which offer items to attempt\n * to aggregate when preparing executions.\n * @param considerationFulfillments An array of FulfillmentComponent arrays\n * indicating which consideration items to\n * attempt to aggregate when preparing\n * executions.\n * @param fulfillerConduitKey A bytes32 value indicating what conduit,\n * if any, to source the fulfiller's token\n * approvals from. The zero hash signifies\n * that no conduit should be used, with\n * direct approvals set on this contract.\n * @param maximumFulfilled The maximum number of orders to fulfill.\n *\n * @return availableOrders An array of booleans indicating if each order\n * with an index corresponding to the index of the\n * returned boolean was fulfillable or not.\n * @return executions An array of elements indicating the sequence of\n * transfers performed as part of matching the given\n * orders.\n */\n function fulfillAvailableOrders(\n Order[] calldata orders,\n FulfillmentComponent[][] calldata offerFulfillments,\n FulfillmentComponent[][] calldata considerationFulfillments,\n bytes32 fulfillerConduitKey,\n uint256 maximumFulfilled\n )\n external\n payable\n returns (bool[] memory availableOrders, Execution[] memory executions);\n\n /**\n * @notice Attempt to fill a group of orders, fully or partially, with an\n * arbitrary number of items for offer and consideration per order\n * alongside criteria resolvers containing specific token\n * identifiers and associated proofs. Any order that is not\n * currently active, has already been fully filled, or has been\n * cancelled will be omitted. Remaining offer and consideration\n * items will then be aggregated where possible as indicated by the\n * supplied offer and consideration component arrays and aggregated\n * items will be transferred to the fulfiller or to each intended\n * recipient, respectively. Note that a failing item transfer or an\n * issue with order formatting will cause the entire batch to fail.\n *\n * @param advancedOrders The orders to fulfill along with the\n * fraction of those orders to attempt to\n * fill. Note that both the offerer and the\n * fulfiller must first approve this\n * contract (or their preferred conduit if\n * indicated by the order) to transfer any\n * relevant tokens on their behalf and that\n * contracts must implement\n * `onERC1155Received` to enable receipt of\n * ERC1155 tokens as consideration. Also\n * note that all offer and consideration\n * components must have no remainder after\n * multiplication of the respective amount\n * with the supplied fraction for an\n * order's partial fill amount to be\n * considered valid.\n * @param criteriaResolvers An array where each element contains a\n * reference to a specific offer or\n * consideration, a token identifier, and a\n * proof that the supplied token identifier\n * is contained in the merkle root held by\n * the item in question's criteria element.\n * Note that an empty criteria indicates\n * that any (transferable) token\n * identifier on the token in question is\n * valid and that no associated proof needs\n * to be supplied.\n * @param offerFulfillments An array of FulfillmentComponent arrays\n * indicating which offer items to attempt\n * to aggregate when preparing executions.\n * @param considerationFulfillments An array of FulfillmentComponent arrays\n * indicating which consideration items to\n * attempt to aggregate when preparing\n * executions.\n * @param fulfillerConduitKey A bytes32 value indicating what conduit,\n * if any, to source the fulfiller's token\n * approvals from. The zero hash signifies\n * that no conduit should be used, with\n * direct approvals set on this contract.\n * @param recipient The intended recipient for all received\n * items, with `address(0)` indicating that\n * the caller should receive the items.\n * @param maximumFulfilled The maximum number of orders to fulfill.\n *\n * @return availableOrders An array of booleans indicating if each order\n * with an index corresponding to the index of the\n * returned boolean was fulfillable or not.\n * @return executions An array of elements indicating the sequence of\n * transfers performed as part of matching the given\n * orders.\n */\n function fulfillAvailableAdvancedOrders(\n AdvancedOrder[] calldata advancedOrders,\n CriteriaResolver[] calldata criteriaResolvers,\n FulfillmentComponent[][] calldata offerFulfillments,\n FulfillmentComponent[][] calldata considerationFulfillments,\n bytes32 fulfillerConduitKey,\n address recipient,\n uint256 maximumFulfilled\n )\n external\n payable\n returns (bool[] memory availableOrders, Execution[] memory executions);\n\n /**\n * @notice Match an arbitrary number of orders, each with an arbitrary\n * number of items for offer and consideration along with as set of\n * fulfillments allocating offer components to consideration\n * components. Note that this function does not support\n * criteria-based or partial filling of orders (though filling the\n * remainder of a partially-filled order is supported).\n *\n * @param orders The orders to match. Note that both the offerer and\n * fulfiller on each order must first approve this\n * contract (or their conduit if indicated by the order)\n * to transfer any relevant tokens on their behalf and\n * each consideration recipient must implement\n * `onERC1155Received` to enable ERC1155 token receipt.\n * @param fulfillments An array of elements allocating offer components to\n * consideration components. Note that each\n * consideration component must be fully met for the\n * match operation to be valid.\n *\n * @return executions An array of elements indicating the sequence of\n * transfers performed as part of matching the given\n * orders.\n */\n function matchOrders(\n Order[] calldata orders,\n Fulfillment[] calldata fulfillments\n ) external payable returns (Execution[] memory executions);\n\n /**\n * @notice Match an arbitrary number of full or partial orders, each with an\n * arbitrary number of items for offer and consideration, supplying\n * criteria resolvers containing specific token identifiers and\n * associated proofs as well as fulfillments allocating offer\n * components to consideration components.\n *\n * @param orders The advanced orders to match. Note that both the\n * offerer and fulfiller on each order must first\n * approve this contract (or a preferred conduit if\n * indicated by the order) to transfer any relevant\n * tokens on their behalf and each consideration\n * recipient must implement `onERC1155Received` in\n * order to receive ERC1155 tokens. Also note that\n * the offer and consideration components for each\n * order must have no remainder after multiplying\n * the respective amount with the supplied fraction\n * in order for the group of partial fills to be\n * considered valid.\n * @param criteriaResolvers An array where each element contains a reference\n * to a specific order as well as that order's\n * offer or consideration, a token identifier, and\n * a proof that the supplied token identifier is\n * contained in the order's merkle root. Note that\n * an empty root indicates that any (transferable)\n * token identifier is valid and that no associated\n * proof needs to be supplied.\n * @param fulfillments An array of elements allocating offer components\n * to consideration components. Note that each\n * consideration component must be fully met in\n * order for the match operation to be valid.\n *\n * @return executions An array of elements indicating the sequence of\n * transfers performed as part of matching the given\n * orders.\n */\n function matchAdvancedOrders(\n AdvancedOrder[] calldata orders,\n CriteriaResolver[] calldata criteriaResolvers,\n Fulfillment[] calldata fulfillments\n ) external payable returns (Execution[] memory executions);\n\n /**\n * @notice Cancel an arbitrary number of orders. Note that only the offerer\n * or the zone of a given order may cancel it. Callers should ensure\n * that the intended order was cancelled by calling `getOrderStatus`\n * and confirming that `isCancelled` returns `true`.\n *\n * @param orders The orders to cancel.\n *\n * @return cancelled A boolean indicating whether the supplied orders have\n * been successfully cancelled.\n */\n function cancel(OrderComponents[] calldata orders)\n external\n returns (bool cancelled);\n\n /**\n * @notice Validate an arbitrary number of orders, thereby registering their\n * signatures as valid and allowing the fulfiller to skip signature\n * verification on fulfillment. Note that validated orders may still\n * be unfulfillable due to invalid item amounts or other factors;\n * callers should determine whether validated orders are fulfillable\n * by simulating the fulfillment call prior to execution. Also note\n * that anyone can validate a signed order, but only the offerer can\n * validate an order without supplying a signature.\n *\n * @param orders The orders to validate.\n *\n * @return validated A boolean indicating whether the supplied orders have\n * been successfully validated.\n */\n function validate(Order[] calldata orders)\n external\n returns (bool validated);\n\n /**\n * @notice Cancel all orders from a given offerer with a given zone in bulk\n * by incrementing a counter. Note that only the offerer may\n * increment the counter.\n *\n * @return newCounter The new counter.\n */\n function incrementCounter() external returns (uint256 newCounter);\n\n /**\n * @notice Retrieve the order hash for a given order.\n *\n * @param order The components of the order.\n *\n * @return orderHash The order hash.\n */\n function getOrderHash(OrderComponents calldata order)\n external\n view\n returns (bytes32 orderHash);\n\n /**\n * @notice Retrieve the status of a given order by hash, including whether\n * the order has been cancelled or validated and the fraction of the\n * order that has been filled.\n *\n * @param orderHash The order hash in question.\n *\n * @return isValidated A boolean indicating whether the order in question\n * has been validated (i.e. previously approved or\n * partially filled).\n * @return isCancelled A boolean indicating whether the order in question\n * has been cancelled.\n * @return totalFilled The total portion of the order that has been filled\n * (i.e. the \"numerator\").\n * @return totalSize The total size of the order that is either filled or\n * unfilled (i.e. the \"denominator\").\n */\n function getOrderStatus(bytes32 orderHash)\n external\n view\n returns (\n bool isValidated,\n bool isCancelled,\n uint256 totalFilled,\n uint256 totalSize\n );\n\n /**\n * @notice Retrieve the current counter for a given offerer.\n *\n * @param offerer The offerer in question.\n *\n * @return counter The current counter.\n */\n function getCounter(address offerer)\n external\n view\n returns (uint256 counter);\n\n /**\n * @notice Retrieve configuration information for this contract.\n *\n * @return version The contract version.\n * @return domainSeparator The domain separator for this contract.\n * @return conduitController The conduit Controller set for this contract.\n */\n function information()\n external\n view\n returns (\n string memory version,\n bytes32 domainSeparator,\n address conduitController\n );\n\n /**\n * @notice Retrieve the name of this contract.\n *\n * @return contractName The name of this contract.\n */\n function name() external view returns (string memory contractName);\n}\n" }, "contracts/dependencies/looksrare/contracts/interfaces/ILooksRareExchange.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {OrderTypes} from \"../libraries/OrderTypes.sol\";\n\ninterface ILooksRareExchange {\n function matchAskWithTakerBidUsingETHAndWETH(\n OrderTypes.TakerOrder calldata takerBid,\n OrderTypes.MakerOrder calldata makerAsk\n ) external payable;\n\n function matchAskWithTakerBid(OrderTypes.TakerOrder calldata takerBid, OrderTypes.MakerOrder calldata makerAsk)\n external;\n\n function matchBidWithTakerAsk(OrderTypes.TakerOrder calldata takerAsk, OrderTypes.MakerOrder calldata makerBid)\n external;\n}\n" }, "contracts/dependencies/looksrare/contracts/libraries/SignatureChecker.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {Address} from \"../../../openzeppelin/contracts/Address.sol\";\nimport {IERC1271} from \"../../../openzeppelin/contracts/IERC1271.sol\";\n\n/**\n * @title SignatureChecker\n * @notice This library allows verification of signatures for both EOAs and contracts.\n */\nlibrary SignatureChecker {\n /**\n * @notice Recovers the signer of a signature (for EOA)\n * @param hash the hash containing the signed mesage\n * @param v parameter (27 or 28). This prevents maleability since the public key recovery equation has two possible solutions.\n * @param r parameter\n * @param s parameter\n */\n function recover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address) {\n // https://ethereum.stackexchange.com/questions/83174/is-it-best-practice-to-check-signature-malleability-in-ecrecover\n // https://crypto.iacr.org/2019/affevents/wac/medias/Heninger-BiasedNonceSense.pdf\n require(\n uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,\n \"Signature: Invalid s parameter\"\n );\n\n require(v == 27 || v == 28, \"Signature: Invalid v parameter\");\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n require(signer != address(0), \"Signature: Invalid signer\");\n\n return signer;\n }\n\n /**\n * @notice Returns whether the signer matches the signed message\n * @param hash the hash containing the signed mesage\n * @param signer the signer address to confirm message validity\n * @param v parameter (27 or 28)\n * @param r parameter\n * @param s parameter\n * @param domainSeparator paramer to prevent signature being executed in other chains and environments\n * @return true --> if valid // false --> if invalid\n */\n function verify(\n bytes32 hash,\n address signer,\n uint8 v,\n bytes32 r,\n bytes32 s,\n bytes32 domainSeparator\n ) internal view returns (bool) {\n // \\x19\\x01 is the standardized encoding prefix\n // https://eips.ethereum.org/EIPS/eip-712#specification\n bytes32 digest = keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, hash));\n if (Address.isContract(signer)) {\n // 0x1626ba7e is the interfaceId for signature contracts (see IERC1271)\n return IERC1271(signer).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e;\n } else {\n return recover(digest, v, r, s) == signer;\n }\n }\n}\n" }, "contracts/protocol/libraries/configuration/UserConfiguration.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {ReserveConfiguration} from \"./ReserveConfiguration.sol\";\n\n/**\n * @title UserConfiguration library\n *\n * @notice Implements the bitmap logic to handle the user configuration\n */\nlibrary UserConfiguration {\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n\n uint256 internal constant BORROWING_MASK =\n 0x5555555555555555555555555555555555555555555555555555555555555555;\n uint256 internal constant COLLATERAL_MASK =\n 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA;\n\n /**\n * @notice Sets if the user is borrowing the reserve identified by reserveIndex\n * @param self The configuration object\n * @param reserveIndex The index of the reserve in the bitmap\n * @param borrowing True if the user is borrowing the reserve, false otherwise\n **/\n function setBorrowing(\n DataTypes.UserConfigurationMap storage self,\n uint256 reserveIndex,\n bool borrowing\n ) internal {\n unchecked {\n require(\n reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT,\n Errors.INVALID_RESERVE_INDEX\n );\n uint256 bit = 1 << (reserveIndex << 1);\n if (borrowing) {\n self.data |= bit;\n } else {\n self.data &= ~bit;\n }\n }\n }\n\n /**\n * @notice Sets if the user is using as collateral the reserve identified by reserveIndex\n * @param self The configuration object\n * @param reserveIndex The index of the reserve in the bitmap\n * @param usingAsCollateral True if the user is using the reserve as collateral, false otherwise\n **/\n function setUsingAsCollateral(\n DataTypes.UserConfigurationMap storage self,\n uint256 reserveIndex,\n bool usingAsCollateral\n ) internal {\n unchecked {\n require(\n reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT,\n Errors.INVALID_RESERVE_INDEX\n );\n uint256 bit = 1 << ((reserveIndex << 1) + 1);\n if (usingAsCollateral) {\n self.data |= bit;\n } else {\n self.data &= ~bit;\n }\n }\n }\n\n /**\n * @notice Returns if a user has been using the reserve for borrowing or as collateral\n * @param self The configuration object\n * @param reserveIndex The index of the reserve in the bitmap\n * @return True if the user has been using a reserve for borrowing or as collateral, false otherwise\n **/\n function isUsingAsCollateralOrBorrowing(\n DataTypes.UserConfigurationMap memory self,\n uint256 reserveIndex\n ) internal pure returns (bool) {\n unchecked {\n require(\n reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT,\n Errors.INVALID_RESERVE_INDEX\n );\n return (self.data >> (reserveIndex << 1)) & 3 != 0;\n }\n }\n\n /**\n * @notice Validate a user has been using the reserve for borrowing\n * @param self The configuration object\n * @param reserveIndex The index of the reserve in the bitmap\n * @return True if the user has been using a reserve for borrowing, false otherwise\n **/\n function isBorrowing(\n DataTypes.UserConfigurationMap memory self,\n uint256 reserveIndex\n ) internal pure returns (bool) {\n unchecked {\n require(\n reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT,\n Errors.INVALID_RESERVE_INDEX\n );\n return (self.data >> (reserveIndex << 1)) & 1 != 0;\n }\n }\n\n /**\n * @notice Validate a user has been using the reserve as collateral\n * @param self The configuration object\n * @param reserveIndex The index of the reserve in the bitmap\n * @return True if the user has been using a reserve as collateral, false otherwise\n **/\n function isUsingAsCollateral(\n DataTypes.UserConfigurationMap memory self,\n uint256 reserveIndex\n ) internal pure returns (bool) {\n unchecked {\n require(\n reserveIndex < ReserveConfiguration.MAX_RESERVES_COUNT,\n Errors.INVALID_RESERVE_INDEX\n );\n return (self.data >> ((reserveIndex << 1) + 1)) & 1 != 0;\n }\n }\n\n /**\n * @notice Checks if a user has been supplying only one reserve as collateral\n * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0\n * @param self The configuration object\n * @return True if the user has been supplying as collateral one reserve, false otherwise\n **/\n function isUsingAsCollateralOne(DataTypes.UserConfigurationMap memory self)\n internal\n pure\n returns (bool)\n {\n uint256 collateralData = self.data & COLLATERAL_MASK;\n return\n collateralData != 0 && (collateralData & (collateralData - 1) == 0);\n }\n\n /**\n * @notice Checks if a user has been supplying any reserve as collateral\n * @param self The configuration object\n * @return True if the user has been supplying as collateral any reserve, false otherwise\n **/\n function isUsingAsCollateralAny(DataTypes.UserConfigurationMap memory self)\n internal\n pure\n returns (bool)\n {\n return self.data & COLLATERAL_MASK != 0;\n }\n\n /**\n * @notice Checks if a user has been borrowing only one asset\n * @dev this uses a simple trick - if a number is a power of two (only one bit set) then n & (n - 1) == 0\n * @param self The configuration object\n * @return True if the user has been supplying as collateral one reserve, false otherwise\n **/\n function isBorrowingOne(DataTypes.UserConfigurationMap memory self)\n internal\n pure\n returns (bool)\n {\n uint256 borrowingData = self.data & BORROWING_MASK;\n return borrowingData != 0 && (borrowingData & (borrowingData - 1) == 0);\n }\n\n /**\n * @notice Checks if a user has been borrowing from any reserve\n * @param self The configuration object\n * @return True if the user has been borrowing any reserve, false otherwise\n **/\n function isBorrowingAny(DataTypes.UserConfigurationMap memory self)\n internal\n pure\n returns (bool)\n {\n return self.data & BORROWING_MASK != 0;\n }\n\n /**\n * @notice Checks if a user has not been using any reserve for borrowing or supply\n * @param self The configuration object\n * @return True if the user has not been borrowing or supplying any reserve, false otherwise\n **/\n function isEmpty(DataTypes.UserConfigurationMap memory self)\n internal\n pure\n returns (bool)\n {\n return self.data == 0;\n }\n\n /**\n * @notice Returns the siloed borrowing state for the user\n * @param self The configuration object\n * @param reservesData The data of all the reserves\n * @param reservesList The reserve list\n * @return True if the user has borrowed a siloed asset, false otherwise\n * @return The address of the only borrowed asset\n */\n function getSiloedBorrowingState(\n DataTypes.UserConfigurationMap memory self,\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList\n ) internal view returns (bool, address) {\n if (isBorrowingOne(self)) {\n uint256 assetId = _getFirstAssetIdByMask(self, BORROWING_MASK);\n address assetAddress = reservesList[assetId];\n if (reservesData[assetAddress].configuration.getSiloedBorrowing()) {\n return (true, assetAddress);\n }\n }\n\n return (false, address(0));\n }\n\n /**\n * @notice Returns the address of the first asset flagged in the bitmap given the corresponding bitmask\n * @param self The configuration object\n * @return The index of the first asset flagged in the bitmap once the corresponding mask is applied\n */\n function _getFirstAssetIdByMask(\n DataTypes.UserConfigurationMap memory self,\n uint256 mask\n ) internal pure returns (uint256) {\n unchecked {\n uint256 bitmapData = self.data & mask;\n uint256 firstAssetPosition = bitmapData & ~(bitmapData - 1);\n uint256 id;\n\n while ((firstAssetPosition >>= 2) != 0) {\n id += 1;\n }\n return id;\n }\n }\n}\n" }, "contracts/interfaces/IVariableDebtToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IScaledBalanceToken} from \"./IScaledBalanceToken.sol\";\nimport {IInitializableDebtToken} from \"./IInitializableDebtToken.sol\";\n\n/**\n * @title IVariableDebtToken\n *\n * @notice Defines the basic interface for a variable debt token.\n **/\ninterface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken {\n /**\n * @notice Mints debt token to the `onBehalfOf` address\n * @param user The address receiving the borrowed underlying, being the delegatee in case\n * of credit delegate, or same as `onBehalfOf` otherwise\n * @param onBehalfOf The address receiving the debt tokens\n * @param amount The amount of debt being minted\n * @param index The variable debt index of the reserve\n * @return True if the previous balance of the user is 0, false otherwise\n * @return The scaled total debt of the reserve\n **/\n function mint(\n address user,\n address onBehalfOf,\n uint256 amount,\n uint256 index\n ) external returns (bool, uint256);\n\n /**\n * @notice Burns user variable debt\n * @dev In some instances, a burn transaction will emit a mint event\n * if the amount to burn is less than the interest that the user accrued\n * @param from The address from which the debt will be burned\n * @param amount The amount getting burned\n * @param index The variable debt index of the reserve\n * @return The scaled total debt of the reserve\n **/\n function burn(\n address from,\n uint256 amount,\n uint256 index\n ) external returns (uint256);\n\n /**\n * @notice Returns the address of the underlying asset of this debtToken (E.g. WETH for variableDebtWETH)\n * @return The address of the underlying asset\n **/\n function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n}\n" }, "contracts/interfaces/IReserveInterestRateStrategy.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {DataTypes} from \"../protocol/libraries/types/DataTypes.sol\";\n\n/**\n * @title IReserveInterestRateStrategy\n *\n * @notice Interface for the calculation of the interest rates\n */\ninterface IReserveInterestRateStrategy {\n /**\n * @notice Returns the base variable borrow rate\n * @return The base variable borrow rate, expressed in ray\n **/\n function getBaseVariableBorrowRate() external view returns (uint256);\n\n /**\n * @notice Returns the maximum variable borrow rate\n * @return The maximum variable borrow rate, expressed in ray\n **/\n function getMaxVariableBorrowRate() external view returns (uint256);\n\n /**\n * @notice Calculates the interest rates depending on the reserve's state and configurations\n * @param params The parameters needed to calculate interest rates\n * @return liquidityRate The liquidity rate expressed in rays\n * @return variableBorrowRate The variable borrow rate expressed in rays\n **/\n function calculateInterestRates(\n DataTypes.CalculateInterestRatesParams memory params\n ) external view returns (uint256, uint256);\n}\n" }, "contracts/dependencies/gnosis/contracts/GPv2SafeERC20.sol": { "content": "// SPDX-License-Identifier: LGPL-3.0-or-later\npragma solidity 0.8.10;\n\nimport {IERC20} from \"../../openzeppelin/contracts/IERC20.sol\";\n\n/// @title Gnosis Protocol v2 Safe ERC20 Transfer Library\n/// @author Gnosis Developers\n/// @dev Gas-efficient version of Openzeppelin's SafeERC20 contract.\nlibrary GPv2SafeERC20 {\n /// @dev Wrapper around a call to the ERC20 function `transfer` that reverts\n /// also when the token returns `false`.\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n bytes4 selector_ = token.transfer.selector;\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let freeMemoryPointer := mload(0x40)\n mstore(freeMemoryPointer, selector_)\n mstore(\n add(freeMemoryPointer, 4),\n and(to, 0xffffffffffffffffffffffffffffffffffffffff)\n )\n mstore(add(freeMemoryPointer, 36), value)\n\n if iszero(call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)) {\n returndatacopy(0, 0, returndatasize())\n revert(0, returndatasize())\n }\n }\n\n require(getLastTransferResult(token), \"GPv2: failed transfer\");\n }\n\n /// @dev Wrapper around a call to the ERC20 function `transferFrom` that\n /// reverts also when the token returns `false`.\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n bytes4 selector_ = token.transferFrom.selector;\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let freeMemoryPointer := mload(0x40)\n mstore(freeMemoryPointer, selector_)\n mstore(\n add(freeMemoryPointer, 4),\n and(from, 0xffffffffffffffffffffffffffffffffffffffff)\n )\n mstore(\n add(freeMemoryPointer, 36),\n and(to, 0xffffffffffffffffffffffffffffffffffffffff)\n )\n mstore(add(freeMemoryPointer, 68), value)\n\n if iszero(call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)) {\n returndatacopy(0, 0, returndatasize())\n revert(0, returndatasize())\n }\n }\n\n require(getLastTransferResult(token), \"GPv2: failed transferFrom\");\n }\n\n /// @dev Verifies that the last return was a successful `transfer*` call.\n /// This is done by checking that the return data is either empty, or\n /// is a valid ABI encoded boolean.\n function getLastTransferResult(IERC20 token)\n private\n view\n returns (bool success)\n {\n // NOTE: Inspecting previous return data requires assembly. Note that\n // we write the return data to memory 0 in the case where the return\n // data size is 32, this is OK since the first 64 bytes of memory are\n // reserved by Solidy as a scratch space that can be used within\n // assembly blocks.\n // \n // solhint-disable-next-line no-inline-assembly\n assembly {\n /// @dev Revert with an ABI encoded Solidity error with a message\n /// that fits into 32-bytes.\n ///\n /// An ABI encoded Solidity error has the following memory layout:\n ///\n /// ------------+----------------------------------\n /// byte range | value\n /// ------------+----------------------------------\n /// 0x00..0x04 | selector(\"Error(string)\")\n /// 0x04..0x24 | string offset (always 0x20)\n /// 0x24..0x44 | string length\n /// 0x44..0x64 | string value, padded to 32-bytes\n function revertWithMessage(length, message) {\n mstore(0x00, \"\\x08\\xc3\\x79\\xa0\")\n mstore(0x04, 0x20)\n mstore(0x24, length)\n mstore(0x44, message)\n revert(0x00, 0x64)\n }\n\n switch returndatasize()\n // Non-standard ERC20 transfer without return.\n case 0 {\n // NOTE: When the return data size is 0, verify that there\n // is code at the address. This is done in order to maintain\n // compatibility with Solidity calling conventions.\n // \n if iszero(extcodesize(token)) {\n revertWithMessage(20, \"GPv2: not a contract\")\n }\n\n success := 1\n }\n // Standard ERC20 transfer returning boolean success value.\n case 32 {\n returndatacopy(0, 0, returndatasize())\n\n // NOTE: For ABI encoding v1, any non-zero value is accepted\n // as `true` for a boolean. In order to stay compatible with\n // OpenZeppelin's `SafeERC20` library which is known to work\n // with the existing ERC20 implementation we care about,\n // make sure we return success for any non-zero return value\n // from the `transfer*` call.\n success := iszero(iszero(mload(0)))\n }\n default {\n revertWithMessage(31, \"GPv2: malformed transfer result\")\n }\n }\n }\n}\n" }, "contracts/protocol/libraries/math/MathUtils.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {WadRayMath} from \"./WadRayMath.sol\";\n\n/**\n * @title MathUtils library\n *\n * @notice Provides functions to perform linear and compounded interest calculations\n */\nlibrary MathUtils {\n using WadRayMath for uint256;\n\n /// @dev Ignoring leap years\n uint256 internal constant SECONDS_PER_YEAR = 365 days;\n\n /**\n * @dev Function to calculate the interest accumulated using a linear interest rate formula\n * @param rate The interest rate, in ray\n * @param lastUpdateTimestamp The timestamp of the last update of the interest\n * @return The interest rate linearly accumulated during the timeDelta, in ray\n **/\n function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)\n internal\n view\n returns (uint256)\n {\n //solium-disable-next-line\n uint256 result = rate *\n (block.timestamp - uint256(lastUpdateTimestamp));\n unchecked {\n result = result / SECONDS_PER_YEAR;\n }\n\n return WadRayMath.RAY + result;\n }\n\n /**\n * @dev Function to calculate the interest using a compounded interest rate formula\n * To avoid expensive exponentiation, the calculation is performed using a binomial approximation:\n *\n * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...\n *\n * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great\n * gas cost reductions. The whitepaper contains reference to the approximation and a table showing the margin of\n * error per different time periods\n *\n * @param rate The interest rate, in ray\n * @param lastUpdateTimestamp The timestamp of the last update of the interest\n * @return The interest rate compounded during the timeDelta, in ray\n **/\n function calculateCompoundedInterest(\n uint256 rate,\n uint40 lastUpdateTimestamp,\n uint256 currentTimestamp\n ) internal pure returns (uint256) {\n //solium-disable-next-line\n uint256 exp = currentTimestamp - uint256(lastUpdateTimestamp);\n\n if (exp == 0) {\n return WadRayMath.RAY;\n }\n\n uint256 expMinusOne;\n uint256 expMinusTwo;\n uint256 basePowerTwo;\n uint256 basePowerThree;\n unchecked {\n expMinusOne = exp - 1;\n\n expMinusTwo = exp > 2 ? exp - 2 : 0;\n\n basePowerTwo =\n rate.rayMul(rate) /\n (SECONDS_PER_YEAR * SECONDS_PER_YEAR);\n basePowerThree = basePowerTwo.rayMul(rate) / SECONDS_PER_YEAR;\n }\n\n uint256 secondTerm = exp * expMinusOne * basePowerTwo;\n unchecked {\n secondTerm /= 2;\n }\n uint256 thirdTerm = exp * expMinusOne * expMinusTwo * basePowerThree;\n unchecked {\n thirdTerm /= 6;\n }\n\n return\n WadRayMath.RAY +\n (rate * exp) /\n SECONDS_PER_YEAR +\n secondTerm +\n thirdTerm;\n }\n\n /**\n * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp\n * @param rate The interest rate (in ray)\n * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated\n * @return The interest rate compounded between lastUpdateTimestamp and current block timestamp, in ray\n **/\n function calculateCompoundedInterest(\n uint256 rate,\n uint40 lastUpdateTimestamp\n ) internal view returns (uint256) {\n return\n calculateCompoundedInterest(\n rate,\n lastUpdateTimestamp,\n block.timestamp\n );\n }\n}\n" }, "contracts/protocol/libraries/math/WadRayMath.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\n/**\n * @title WadRayMath library\n *\n * @notice Provides functions to perform calculations with Wad and Ray units\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits of precision) and rays (decimal numbers\n * with 27 digits of precision)\n * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down.\n **/\nlibrary WadRayMath {\n // HALF_WAD and HALF_RAY expressed with extended notation as constant with operations are not supported in Yul assembly\n uint256 internal constant WAD = 1e18;\n uint256 internal constant HALF_WAD = 0.5e18;\n\n uint256 internal constant RAY = 1e27;\n uint256 internal constant HALF_RAY = 0.5e27;\n\n uint256 internal constant WAD_RAY_RATIO = 1e9;\n\n /**\n * @dev Multiplies two wad, rounding half up to the nearest wad\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Wad\n * @param b Wad\n * @return c = a*b, in wad\n **/\n function wadMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n // to avoid overflow, a <= (type(uint256).max - HALF_WAD) / b\n assembly {\n if iszero(\n or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_WAD), b))))\n ) {\n revert(0, 0)\n }\n\n c := div(add(mul(a, b), HALF_WAD), WAD)\n }\n }\n\n /**\n * @dev Divides two wad, rounding half up to the nearest wad\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Wad\n * @param b Wad\n * @return c = a/b, in wad\n **/\n function wadDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n // to avoid overflow, a <= (type(uint256).max - halfB) / WAD\n assembly {\n if or(\n iszero(b),\n iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), WAD))))\n ) {\n revert(0, 0)\n }\n\n c := div(add(mul(a, WAD), div(b, 2)), b)\n }\n }\n\n /**\n * @notice Multiplies two ray, rounding half up to the nearest ray\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Ray\n * @param b Ray\n * @return c = a raymul b\n **/\n function rayMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n // to avoid overflow, a <= (type(uint256).max - HALF_RAY) / b\n assembly {\n if iszero(\n or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_RAY), b))))\n ) {\n revert(0, 0)\n }\n\n c := div(add(mul(a, b), HALF_RAY), RAY)\n }\n }\n\n /**\n * @notice Divides two ray, rounding half up to the nearest ray\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Ray\n * @param b Ray\n * @return c = a raydiv b\n **/\n function rayDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n // to avoid overflow, a <= (type(uint256).max - halfB) / RAY\n assembly {\n if or(\n iszero(b),\n iszero(iszero(gt(a, div(sub(not(0), div(b, 2)), RAY))))\n ) {\n revert(0, 0)\n }\n\n c := div(add(mul(a, RAY), div(b, 2)), b)\n }\n }\n\n /**\n * @dev Casts ray down to wad\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Ray\n * @return b = a converted to wad, rounded half up to the nearest wad\n **/\n function rayToWad(uint256 a) internal pure returns (uint256 b) {\n assembly {\n b := div(a, WAD_RAY_RATIO)\n let remainder := mod(a, WAD_RAY_RATIO)\n if iszero(lt(remainder, div(WAD_RAY_RATIO, 2))) {\n b := add(b, 1)\n }\n }\n }\n\n /**\n * @dev Converts wad up to ray\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param a Wad\n * @return b = a converted in ray\n **/\n function wadToRay(uint256 a) internal pure returns (uint256 b) {\n // to avoid overflow, b/WAD_RAY_RATIO == a\n assembly {\n b := mul(a, WAD_RAY_RATIO)\n\n if iszero(eq(div(b, WAD_RAY_RATIO), a)) {\n revert(0, 0)\n }\n }\n }\n}\n" }, "contracts/protocol/libraries/math/PercentageMath.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\n/**\n * @title PercentageMath library\n *\n * @notice Provides functions to perform percentage calculations\n * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR\n * @dev Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down.\n **/\nlibrary PercentageMath {\n // Maximum percentage factor (100.00%)\n uint256 internal constant PERCENTAGE_FACTOR = 1e4;\n\n // Half percentage factor (50.00%)\n uint256 internal constant HALF_PERCENTAGE_FACTOR = 0.5e4;\n\n /**\n * @notice Executes a percentage multiplication\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param value The value of which the percentage needs to be calculated\n * @param percentage The percentage of the value to be calculated\n * @return result value percentmul percentage\n **/\n function percentMul(uint256 value, uint256 percentage)\n internal\n pure\n returns (uint256 result)\n {\n // to avoid overflow, value <= (type(uint256).max - HALF_PERCENTAGE_FACTOR) / percentage\n assembly {\n if iszero(\n or(\n iszero(percentage),\n iszero(\n gt(\n value,\n div(sub(not(0), HALF_PERCENTAGE_FACTOR), percentage)\n )\n )\n )\n ) {\n revert(0, 0)\n }\n\n result := div(\n add(mul(value, percentage), HALF_PERCENTAGE_FACTOR),\n PERCENTAGE_FACTOR\n )\n }\n }\n\n /**\n * @notice Executes a percentage division\n * @dev assembly optimized for improved gas savings, see https://twitter.com/transmissions11/status/1451131036377571328\n * @param value The value of which the percentage needs to be calculated\n * @param percentage The percentage of the value to be calculated\n * @return result value percentdiv percentage\n **/\n function percentDiv(uint256 value, uint256 percentage)\n internal\n pure\n returns (uint256 result)\n {\n // to avoid overflow, value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR\n assembly {\n if or(\n iszero(percentage),\n iszero(\n iszero(\n gt(\n value,\n div(\n sub(not(0), div(percentage, 2)),\n PERCENTAGE_FACTOR\n )\n )\n )\n )\n ) {\n revert(0, 0)\n }\n\n result := div(\n add(mul(value, PERCENTAGE_FACTOR), div(percentage, 2)),\n percentage\n )\n }\n }\n}\n" }, "contracts/interfaces/IScaledBalanceToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title IScaledBalanceToken\n *\n * @notice Defines the basic interface for a scaledbalance token.\n **/\ninterface IScaledBalanceToken {\n /**\n * @dev Emitted after the mint action\n * @param caller The address performing the mint\n * @param onBehalfOf The address of the user that will receive the minted scaled balance tokens\n * @param value The amount being minted (user entered amount + balance increase from interest)\n * @param balanceIncrease The increase in balance since the last action of the user\n * @param index The next liquidity index of the reserve\n **/\n event Mint(\n address indexed caller,\n address indexed onBehalfOf,\n uint256 value,\n uint256 balanceIncrease,\n uint256 index\n );\n\n /**\n * @dev Emitted after scaled balance tokens are burned\n * @param from The address from which the scaled tokens will be burned\n * @param target The address that will receive the underlying, if any\n * @param value The amount being burned (user entered amount - balance increase from interest)\n * @param balanceIncrease The increase in balance since the last action of the user\n * @param index The next liquidity index of the reserve\n **/\n event Burn(\n address indexed from,\n address indexed target,\n uint256 value,\n uint256 balanceIncrease,\n uint256 index\n );\n\n /**\n * @notice Returns the scaled balance of the user.\n * @dev The scaled balance is the sum of all the updated stored balance divided by the reserve's liquidity index\n * at the moment of the update\n * @param user The user whose balance is calculated\n * @return The scaled balance of the user\n **/\n function scaledBalanceOf(address user) external view returns (uint256);\n\n /**\n * @notice Returns the scaled balance of the user and the scaled total supply.\n * @param user The address of the user\n * @return The scaled balance of the user\n * @return The scaled total supply\n **/\n function getScaledUserBalanceAndSupply(address user)\n external\n view\n returns (uint256, uint256);\n\n /**\n * @notice Returns the scaled total supply of the scaled balance token. Represents sum(debt/index)\n * @return The scaled total supply\n **/\n function scaledTotalSupply() external view returns (uint256);\n\n /**\n * @notice Returns last index interest was accrued to the user's balance\n * @param user The address of the user\n * @return The last index interest was accrued to the user's balance, expressed in ray\n **/\n function getPreviousIndex(address user) external view returns (uint256);\n}\n" }, "contracts/interfaces/IInitializableDebtToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IRewardController} from \"./IRewardController.sol\";\nimport {IPool} from \"./IPool.sol\";\n\n/**\n * @title IInitializableDebtToken\n *\n * @notice Interface for the initialize function common between debt tokens\n **/\ninterface IInitializableDebtToken {\n /**\n * @dev Emitted when a debt token is initialized\n * @param underlyingAsset The address of the underlying asset\n * @param pool The address of the associated pool\n * @param incentivesController The address of the incentives controller for this xToken\n * @param debtTokenDecimals The decimals of the debt token\n * @param debtTokenName The name of the debt token\n * @param debtTokenSymbol The symbol of the debt token\n * @param params A set of encoded parameters for additional initialization\n **/\n event Initialized(\n address indexed underlyingAsset,\n address indexed pool,\n address incentivesController,\n uint8 debtTokenDecimals,\n string debtTokenName,\n string debtTokenSymbol,\n bytes params\n );\n\n /**\n * @notice Initializes the debt token.\n * @param pool The pool contract that is initializing this contract\n * @param underlyingAsset The address of the underlying asset of this xToken (E.g. WETH for pWETH)\n * @param incentivesController The smart contract managing potential incentives distribution\n * @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's\n * @param debtTokenName The name of the token\n * @param debtTokenSymbol The symbol of the token\n * @param params A set of encoded parameters for additional initialization\n */\n function initialize(\n IPool pool,\n address underlyingAsset,\n IRewardController incentivesController,\n uint8 debtTokenDecimals,\n string memory debtTokenName,\n string memory debtTokenSymbol,\n bytes calldata params\n ) external;\n}\n" }, "contracts/interfaces/IPToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IERC20} from \"../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {IScaledBalanceToken} from \"./IScaledBalanceToken.sol\";\nimport {IInitializablePToken} from \"./IInitializablePToken.sol\";\nimport {IXTokenType} from \"./IXTokenType.sol\";\n\n/**\n * @title IPToken\n *\n * @notice Defines the basic interface for an PToken.\n **/\ninterface IPToken is\n IERC20,\n IScaledBalanceToken,\n IInitializablePToken,\n IXTokenType\n{\n /**\n * @notice Mints `amount` xTokens to `user`\n * @param caller The address performing the mint\n * @param onBehalfOf The address of the user that will receive the minted xTokens\n * @param amount The amount of tokens getting minted\n * @param index The next liquidity index of the reserve\n * @return `true` if the the previous balance of the user was 0\n */\n function mint(\n address caller,\n address onBehalfOf,\n uint256 amount,\n uint256 index\n ) external returns (bool);\n\n /**\n * @notice Burns xTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`\n * @dev In some instances, the mint event could be emitted from a burn transaction\n * if the amount to burn is less than the interest that the user accrued\n * @param from The address from which the xTokens will be burned\n * @param receiverOfUnderlying The address that will receive the underlying\n * @param amount The amount being burned\n * @param index The next liquidity index of the reserve\n **/\n function burn(\n address from,\n address receiverOfUnderlying,\n uint256 amount,\n uint256 index\n ) external;\n\n /**\n * @notice Mints xTokens to the reserve treasury\n * @param amount The amount of tokens getting minted\n * @param index The next liquidity index of the reserve\n */\n function mintToTreasury(uint256 amount, uint256 index) external;\n\n /**\n * @notice Transfers xTokens in the event of a borrow being liquidated, in case the liquidators reclaims the xToken\n * @param from The address getting liquidated, current owner of the xTokens\n * @param to The recipient\n * @param value The amount of tokens getting transferred\n **/\n function transferOnLiquidation(\n address from,\n address to,\n uint256 value\n ) external;\n\n /**\n * @notice Transfers the underlying asset to `target`.\n * @dev Used by the Pool to transfer assets in borrow(), withdraw() and flashLoan()\n * @param user The recipient of the underlying\n * @param amount The amount getting transferred\n **/\n function transferUnderlyingTo(address user, uint256 amount) external;\n\n /**\n * @notice Handles the underlying received by the xToken after the transfer has been completed.\n * @dev The default implementation is empty as with standard ERC20 tokens, nothing needs to be done after the\n * transfer is concluded. However in the future there may be xTokens that allow for example to stake the underlying\n * to receive LM rewards. In that case, `handleRepayment()` would perform the staking of the underlying asset.\n * @param user The user executing the repayment\n * @param amount The amount getting repaid\n **/\n function handleRepayment(address user, uint256 amount) external;\n\n /**\n * @notice Allow passing a signed message to approve spending\n * @dev implements the permit function as for\n * https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md\n * @param owner The owner of the funds\n * @param spender The spender\n * @param value The amount\n * @param deadline The deadline timestamp, type(uint256).max for max deadline\n * @param v Signature param\n * @param s Signature param\n * @param r Signature param\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 * @notice Returns the address of the underlying asset of this xToken (E.g. WETH for pWETH)\n * @return The address of the underlying asset\n **/\n function UNDERLYING_ASSET_ADDRESS() external view returns (address);\n\n /**\n * @notice Returns the address of the ParaSpace treasury, receiving the fees on this xToken.\n * @return Address of the ParaSpace treasury\n **/\n function RESERVE_TREASURY_ADDRESS() external view returns (address);\n\n /**\n * @notice Get the domain separator for the token\n * @dev Return cached value if chainId matches cache, otherwise recomputes separator\n * @return The domain separator of the token at current chain\n */\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n\n /**\n * @notice Returns the nonce for owner.\n * @param owner The address of the owner\n * @return The nonce of the owner\n **/\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @notice Rescue and transfer tokens locked in this contract\n * @param token The address of the token\n * @param to The address of the recipient\n * @param amount The amount of token to transfer\n */\n function rescueTokens(\n address token,\n address to,\n uint256 amount\n ) external;\n}\n" }, "contracts/protocol/libraries/logic/ValidationLogic.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {IERC20} from \"../../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {IERC721} from \"../../../dependencies/openzeppelin/contracts/IERC721.sol\";\nimport {Address} from \"../../../dependencies/openzeppelin/contracts/Address.sol\";\nimport {GPv2SafeERC20} from \"../../../dependencies/gnosis/contracts/GPv2SafeERC20.sol\";\nimport {IReserveInterestRateStrategy} from \"../../../interfaces/IReserveInterestRateStrategy.sol\";\nimport {IScaledBalanceToken} from \"../../../interfaces/IScaledBalanceToken.sol\";\nimport {IPriceOracleGetter} from \"../../../interfaces/IPriceOracleGetter.sol\";\nimport {IPToken} from \"../../../interfaces/IPToken.sol\";\nimport {ICollateralizableERC721} from \"../../../interfaces/ICollateralizableERC721.sol\";\nimport {IAuctionableERC721} from \"../../../interfaces/IAuctionableERC721.sol\";\nimport {INToken} from \"../../../interfaces/INToken.sol\";\nimport {SignatureChecker} from \"../../../dependencies/looksrare/contracts/libraries/SignatureChecker.sol\";\nimport {IPriceOracleSentinel} from \"../../../interfaces/IPriceOracleSentinel.sol\";\nimport {ReserveConfiguration} from \"../configuration/ReserveConfiguration.sol\";\nimport {UserConfiguration} from \"../configuration/UserConfiguration.sol\";\nimport {Errors} from \"../helpers/Errors.sol\";\nimport {WadRayMath} from \"../math/WadRayMath.sol\";\nimport {PercentageMath} from \"../math/PercentageMath.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {ReserveLogic} from \"./ReserveLogic.sol\";\nimport {GenericLogic} from \"./GenericLogic.sol\";\nimport {SafeCast} from \"../../../dependencies/openzeppelin/contracts/SafeCast.sol\";\nimport {IToken} from \"../../../interfaces/IToken.sol\";\nimport {XTokenType, IXTokenType} from \"../../../interfaces/IXTokenType.sol\";\nimport {Helpers} from \"../helpers/Helpers.sol\";\nimport {INonfungiblePositionManager} from \"../../../dependencies/uniswap/INonfungiblePositionManager.sol\";\nimport \"../../../interfaces/INTokenApeStaking.sol\";\n\n/**\n * @title ReserveLogic library\n *\n * @notice Implements functions to validate the different actions of the protocol\n */\nlibrary ValidationLogic {\n using WadRayMath for uint256;\n using PercentageMath for uint256;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n using UserConfiguration for DataTypes.UserConfigurationMap;\n\n // Factor to apply to \"only-variable-debt\" liquidity rate to get threshold for rebalancing, expressed in bps\n // A value of 0.9e4 results in 90%\n uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 0.9e4;\n\n // Minimum health factor allowed under any circumstance\n // A value of 0.95e18 results in 0.95\n uint256 public constant MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD =\n 0.95e18;\n\n /**\n * @dev Minimum health factor to consider a user position healthy\n * A value of 1e18 results in 1\n */\n uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1e18;\n\n /**\n * @notice Validates a supply action.\n * @param reserveCache The cached data of the reserve\n * @param amount The amount to be supplied\n */\n function validateSupply(\n DataTypes.ReserveCache memory reserveCache,\n uint256 amount,\n DataTypes.AssetType assetType\n ) internal view {\n require(amount != 0, Errors.INVALID_AMOUNT);\n\n IXTokenType xToken = IXTokenType(reserveCache.xTokenAddress);\n require(\n xToken.getXTokenType() != XTokenType.PTokenSApe,\n Errors.SAPE_NOT_ALLOWED\n );\n\n (\n bool isActive,\n bool isFrozen,\n ,\n bool isPaused,\n DataTypes.AssetType reserveAssetType\n ) = reserveCache.reserveConfiguration.getFlags();\n\n require(reserveAssetType == assetType, Errors.INVALID_ASSET_TYPE);\n require(isActive, Errors.RESERVE_INACTIVE);\n require(!isPaused, Errors.RESERVE_PAUSED);\n require(!isFrozen, Errors.RESERVE_FROZEN);\n\n uint256 supplyCap = reserveCache.reserveConfiguration.getSupplyCap();\n\n if (assetType == DataTypes.AssetType.ERC20) {\n require(\n supplyCap == 0 ||\n (IPToken(reserveCache.xTokenAddress)\n .scaledTotalSupply()\n .rayMul(reserveCache.nextLiquidityIndex) + amount) <=\n supplyCap *\n (10**reserveCache.reserveConfiguration.getDecimals()),\n Errors.SUPPLY_CAP_EXCEEDED\n );\n } else if (assetType == DataTypes.AssetType.ERC721) {\n require(\n supplyCap == 0 ||\n (INToken(reserveCache.xTokenAddress).totalSupply() +\n amount <=\n supplyCap),\n Errors.SUPPLY_CAP_EXCEEDED\n );\n }\n }\n\n /**\n * @notice Validates a supply action from NToken contract\n * @param reserveCache The cached data of the reserve\n * @param params The params of the supply\n * @param assetType the type of the asset supplied\n */\n function validateSupplyFromNToken(\n DataTypes.ReserveCache memory reserveCache,\n DataTypes.ExecuteSupplyERC721Params memory params,\n DataTypes.AssetType assetType\n ) internal view {\n require(\n msg.sender == reserveCache.xTokenAddress,\n Errors.CALLER_NOT_XTOKEN\n );\n\n uint256 amount = params.tokenData.length;\n validateSupply(reserveCache, amount, assetType);\n\n for (uint256 index = 0; index < amount; index++) {\n // validate that the owner of the underlying asset is the NToken contract\n require(\n IERC721(params.asset).ownerOf(\n params.tokenData[index].tokenId\n ) == reserveCache.xTokenAddress,\n Errors.NOT_THE_OWNER\n );\n // validate that the owner of the ntoken that has the same tokenId is the zero address\n require(\n IERC721(reserveCache.xTokenAddress).ownerOf(\n params.tokenData[index].tokenId\n ) == address(0x0),\n Errors.NOT_THE_OWNER\n );\n }\n }\n\n /**\n * @notice Validates a withdraw action.\n * @param reserveCache The cached data of the reserve\n * @param amount The amount to be withdrawn\n * @param userBalance The balance of the user\n */\n function validateWithdraw(\n DataTypes.ReserveCache memory reserveCache,\n uint256 amount,\n uint256 userBalance\n ) internal pure {\n require(amount != 0, Errors.INVALID_AMOUNT);\n\n require(\n amount <= userBalance,\n Errors.NOT_ENOUGH_AVAILABLE_USER_BALANCE\n );\n\n IXTokenType xToken = IXTokenType(reserveCache.xTokenAddress);\n require(\n xToken.getXTokenType() != XTokenType.PTokenSApe,\n Errors.SAPE_NOT_ALLOWED\n );\n\n (\n bool isActive,\n ,\n ,\n bool isPaused,\n DataTypes.AssetType reserveAssetType\n ) = reserveCache.reserveConfiguration.getFlags();\n\n require(\n reserveAssetType == DataTypes.AssetType.ERC20,\n Errors.INVALID_ASSET_TYPE\n );\n require(isActive, Errors.RESERVE_INACTIVE);\n require(!isPaused, Errors.RESERVE_PAUSED);\n }\n\n function validateWithdrawERC721(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.ReserveCache memory reserveCache,\n address asset,\n uint256[] memory tokenIds\n ) internal view {\n (\n bool isActive,\n ,\n ,\n bool isPaused,\n DataTypes.AssetType reserveAssetType\n ) = reserveCache.reserveConfiguration.getFlags();\n\n require(\n reserveAssetType == DataTypes.AssetType.ERC721,\n Errors.INVALID_ASSET_TYPE\n );\n require(isActive, Errors.RESERVE_INACTIVE);\n require(!isPaused, Errors.RESERVE_PAUSED);\n\n INToken nToken = INToken(reserveCache.xTokenAddress);\n if (nToken.getXTokenType() == XTokenType.NTokenUniswapV3) {\n for (uint256 index = 0; index < tokenIds.length; index++) {\n ValidationLogic.validateForUniswapV3(\n reservesData,\n asset,\n tokenIds[index],\n true,\n true,\n false\n );\n }\n }\n }\n\n struct ValidateBorrowLocalVars {\n uint256 currentLtv;\n uint256 collateralNeededInBaseCurrency;\n uint256 userCollateralInBaseCurrency;\n uint256 userDebtInBaseCurrency;\n uint256 availableLiquidity;\n uint256 healthFactor;\n uint256 totalDebt;\n uint256 totalSupplyVariableDebt;\n uint256 reserveDecimals;\n uint256 borrowCap;\n uint256 amountInBaseCurrency;\n uint256 assetUnit;\n address siloedBorrowingAddress;\n bool isActive;\n bool isFrozen;\n bool isPaused;\n bool borrowingEnabled;\n bool siloedBorrowingEnabled;\n DataTypes.AssetType assetType;\n }\n\n /**\n * @notice Validates a borrow action.\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param params Additional params needed for the validation\n */\n function validateBorrow(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.ValidateBorrowParams memory params\n ) internal view {\n require(params.amount != 0, Errors.INVALID_AMOUNT);\n ValidateBorrowLocalVars memory vars;\n\n (\n vars.isActive,\n vars.isFrozen,\n vars.borrowingEnabled,\n vars.isPaused,\n vars.assetType\n ) = params.reserveCache.reserveConfiguration.getFlags();\n\n require(\n vars.assetType == DataTypes.AssetType.ERC20,\n Errors.INVALID_ASSET_TYPE\n );\n require(vars.isActive, Errors.RESERVE_INACTIVE);\n require(!vars.isPaused, Errors.RESERVE_PAUSED);\n require(!vars.isFrozen, Errors.RESERVE_FROZEN);\n require(vars.borrowingEnabled, Errors.BORROWING_NOT_ENABLED);\n\n require(\n params.priceOracleSentinel == address(0) ||\n IPriceOracleSentinel(params.priceOracleSentinel)\n .isBorrowAllowed(),\n Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED\n );\n\n vars.reserveDecimals = params\n .reserveCache\n .reserveConfiguration\n .getDecimals();\n vars.borrowCap = params\n .reserveCache\n .reserveConfiguration\n .getBorrowCap();\n unchecked {\n vars.assetUnit = 10**vars.reserveDecimals;\n }\n\n if (vars.borrowCap != 0) {\n vars.totalSupplyVariableDebt = params\n .reserveCache\n .currScaledVariableDebt\n .rayMul(params.reserveCache.nextVariableBorrowIndex);\n\n vars.totalDebt = vars.totalSupplyVariableDebt + params.amount;\n\n unchecked {\n require(\n vars.totalDebt <= vars.borrowCap * vars.assetUnit,\n Errors.BORROW_CAP_EXCEEDED\n );\n }\n }\n\n (\n vars.userCollateralInBaseCurrency,\n ,\n vars.userDebtInBaseCurrency,\n vars.currentLtv,\n ,\n ,\n ,\n vars.healthFactor,\n ,\n\n ) = GenericLogic.calculateUserAccountData(\n reservesData,\n reservesList,\n DataTypes.CalculateUserAccountDataParams({\n userConfig: params.userConfig,\n reservesCount: params.reservesCount,\n user: params.userAddress,\n oracle: params.oracle\n })\n );\n\n require(\n vars.userCollateralInBaseCurrency != 0,\n Errors.COLLATERAL_BALANCE_IS_ZERO\n );\n require(vars.currentLtv != 0, Errors.LTV_VALIDATION_FAILED);\n\n require(\n vars.healthFactor > HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n );\n\n vars.amountInBaseCurrency =\n IPriceOracleGetter(params.oracle).getAssetPrice(params.asset) *\n params.amount;\n unchecked {\n vars.amountInBaseCurrency /= vars.assetUnit;\n }\n\n //add the current already borrowed amount to the amount requested to calculate the total collateral needed.\n vars.collateralNeededInBaseCurrency = (vars.userDebtInBaseCurrency +\n vars.amountInBaseCurrency).percentDiv(vars.currentLtv); //LTV is calculated in percentage\n\n require(\n vars.collateralNeededInBaseCurrency <=\n vars.userCollateralInBaseCurrency,\n Errors.COLLATERAL_CANNOT_COVER_NEW_BORROW\n );\n }\n\n /**\n * @notice Validates a repay action.\n * @param reserveCache The cached data of the reserve\n * @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)\n * @param onBehalfOf The address of the user msg.sender is repaying for\n * @param variableDebt The borrow balance of the user\n */\n function validateRepay(\n DataTypes.ReserveCache memory reserveCache,\n uint256 amountSent,\n address onBehalfOf,\n uint256 variableDebt\n ) internal view {\n require(amountSent != 0, Errors.INVALID_AMOUNT);\n require(\n amountSent != type(uint256).max || msg.sender == onBehalfOf,\n Errors.NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF\n );\n\n (\n bool isActive,\n ,\n ,\n bool isPaused,\n DataTypes.AssetType assetType\n ) = reserveCache.reserveConfiguration.getFlags();\n require(isActive, Errors.RESERVE_INACTIVE);\n require(!isPaused, Errors.RESERVE_PAUSED);\n require(\n assetType == DataTypes.AssetType.ERC20,\n Errors.INVALID_ASSET_TYPE\n );\n\n uint256 variableDebtPreviousIndex = IScaledBalanceToken(\n reserveCache.variableDebtTokenAddress\n ).getPreviousIndex(onBehalfOf);\n\n require(\n (variableDebtPreviousIndex < reserveCache.nextVariableBorrowIndex),\n Errors.SAME_BLOCK_BORROW_REPAY\n );\n\n require((variableDebt != 0), Errors.NO_DEBT_OF_SELECTED_TYPE);\n }\n\n /**\n * @notice Validates the action of setting an asset as collateral.\n * @param reserveCache The cached data of the reserve\n * @param userBalance The balance of the user\n */\n function validateSetUseERC20AsCollateral(\n DataTypes.ReserveCache memory reserveCache,\n uint256 userBalance\n ) internal pure {\n require(userBalance != 0, Errors.UNDERLYING_BALANCE_ZERO);\n\n IXTokenType xToken = IXTokenType(reserveCache.xTokenAddress);\n require(\n xToken.getXTokenType() != XTokenType.PTokenSApe,\n Errors.SAPE_NOT_ALLOWED\n );\n\n (\n bool isActive,\n ,\n ,\n bool isPaused,\n DataTypes.AssetType reserveAssetType\n ) = reserveCache.reserveConfiguration.getFlags();\n\n require(\n reserveAssetType == DataTypes.AssetType.ERC20,\n Errors.INVALID_ASSET_TYPE\n );\n require(isActive, Errors.RESERVE_INACTIVE);\n require(!isPaused, Errors.RESERVE_PAUSED);\n }\n\n function validateSetUseERC721AsCollateral(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.ReserveCache memory reserveCache,\n address asset,\n uint256[] calldata tokenIds\n ) internal view {\n (\n bool isActive,\n ,\n ,\n bool isPaused,\n DataTypes.AssetType reserveAssetType\n ) = reserveCache.reserveConfiguration.getFlags();\n\n require(\n reserveAssetType == DataTypes.AssetType.ERC721,\n Errors.INVALID_ASSET_TYPE\n );\n require(isActive, Errors.RESERVE_INACTIVE);\n require(!isPaused, Errors.RESERVE_PAUSED);\n\n INToken nToken = INToken(reserveCache.xTokenAddress);\n if (nToken.getXTokenType() == XTokenType.NTokenUniswapV3) {\n for (uint256 index = 0; index < tokenIds.length; index++) {\n ValidationLogic.validateForUniswapV3(\n reservesData,\n asset,\n tokenIds[index],\n true,\n true,\n false\n );\n }\n }\n }\n\n struct ValidateLiquidateLocalVars {\n bool collateralReserveActive;\n bool collateralReservePaused;\n bool principalReserveActive;\n bool principalReservePaused;\n bool isCollateralEnabled;\n DataTypes.AssetType collateralReserveAssetType;\n }\n\n struct ValidateAuctionLocalVars {\n bool collateralReserveActive;\n bool collateralReservePaused;\n bool isCollateralEnabled;\n DataTypes.AssetType collateralReserveAssetType;\n }\n\n /**\n * @notice Validates the liquidation action.\n * @param userConfig The user configuration mapping\n * @param collateralReserve The reserve data of the collateral\n * @param params Additional parameters needed for the validation\n */\n function validateLiquidateERC20(\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ReserveData storage collateralReserve,\n DataTypes.ValidateLiquidateERC20Params memory params\n ) internal view {\n ValidateLiquidateLocalVars memory vars;\n\n (\n vars.collateralReserveActive,\n ,\n ,\n vars.collateralReservePaused,\n vars.collateralReserveAssetType\n ) = collateralReserve.configuration.getFlags();\n\n require(\n vars.collateralReserveAssetType == DataTypes.AssetType.ERC20,\n Errors.INVALID_ASSET_TYPE\n );\n\n require(\n msg.value == 0 || params.liquidationAsset == params.weth,\n Errors.INVALID_LIQUIDATION_ASSET\n );\n\n require(\n msg.value == 0 || msg.value >= params.actualLiquidationAmount,\n Errors.LIQUIDATION_AMOUNT_NOT_ENOUGH\n );\n\n IXTokenType xToken = IXTokenType(\n params.liquidationAssetReserveCache.xTokenAddress\n );\n require(\n xToken.getXTokenType() != XTokenType.PTokenSApe,\n Errors.SAPE_NOT_ALLOWED\n );\n\n (\n vars.principalReserveActive,\n ,\n ,\n vars.principalReservePaused,\n\n ) = params.liquidationAssetReserveCache.reserveConfiguration.getFlags();\n\n require(\n vars.collateralReserveActive && vars.principalReserveActive,\n Errors.RESERVE_INACTIVE\n );\n require(\n !vars.collateralReservePaused && !vars.principalReservePaused,\n Errors.RESERVE_PAUSED\n );\n\n require(\n params.priceOracleSentinel == address(0) ||\n params.healthFactor <\n MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD ||\n IPriceOracleSentinel(params.priceOracleSentinel)\n .isLiquidationAllowed(),\n Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED\n );\n\n require(\n params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n Errors.HEALTH_FACTOR_NOT_BELOW_THRESHOLD\n );\n\n vars.isCollateralEnabled =\n collateralReserve.configuration.getLiquidationThreshold() != 0 &&\n userConfig.isUsingAsCollateral(collateralReserve.id);\n\n //if collateral isn't enabled as collateral by user, it cannot be liquidated\n require(\n vars.isCollateralEnabled,\n Errors.COLLATERAL_CANNOT_BE_AUCTIONED_OR_LIQUIDATED\n );\n require(\n params.totalDebt != 0,\n Errors.SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER\n );\n }\n\n /**\n * @notice Validates the liquidation action.\n * @param userConfig The user configuration mapping\n * @param collateralReserve The reserve data of the collateral\n * @param params Additional parameters needed for the validation\n */\n function validateLiquidateERC721(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ReserveData storage collateralReserve,\n DataTypes.ValidateLiquidateERC721Params memory params\n ) internal view {\n require(\n params.liquidator != params.borrower,\n Errors.LIQUIDATOR_CAN_NOT_BE_SELF\n );\n\n ValidateLiquidateLocalVars memory vars;\n\n (\n vars.collateralReserveActive,\n ,\n ,\n vars.collateralReservePaused,\n vars.collateralReserveAssetType\n ) = collateralReserve.configuration.getFlags();\n\n require(\n vars.collateralReserveAssetType == DataTypes.AssetType.ERC721,\n Errors.INVALID_ASSET_TYPE\n );\n\n INToken nToken = INToken(collateralReserve.xTokenAddress);\n if (nToken.getXTokenType() == XTokenType.NTokenUniswapV3) {\n ValidationLogic.validateForUniswapV3(\n reservesData,\n params.collateralAsset,\n params.tokenId,\n true,\n true,\n false\n );\n }\n\n (\n vars.principalReserveActive,\n ,\n ,\n vars.principalReservePaused,\n\n ) = params.liquidationAssetReserveCache.reserveConfiguration.getFlags();\n\n require(\n vars.collateralReserveActive && vars.principalReserveActive,\n Errors.RESERVE_INACTIVE\n );\n require(\n !vars.collateralReservePaused && !vars.principalReservePaused,\n Errors.RESERVE_PAUSED\n );\n\n require(\n params.priceOracleSentinel == address(0) ||\n params.healthFactor <\n MINIMUM_HEALTH_FACTOR_LIQUIDATION_THRESHOLD ||\n IPriceOracleSentinel(params.priceOracleSentinel)\n .isLiquidationAllowed(),\n Errors.PRICE_ORACLE_SENTINEL_CHECK_FAILED\n );\n\n if (params.auctionEnabled) {\n require(\n params.healthFactor < params.auctionRecoveryHealthFactor,\n Errors.ERC721_HEALTH_FACTOR_NOT_BELOW_THRESHOLD\n );\n require(\n IAuctionableERC721(params.xTokenAddress).isAuctioned(\n params.tokenId\n ),\n Errors.AUCTION_NOT_STARTED\n );\n } else {\n require(\n params.healthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n Errors.ERC721_HEALTH_FACTOR_NOT_BELOW_THRESHOLD\n );\n }\n\n require(\n params.maxLiquidationAmount >= params.actualLiquidationAmount &&\n (msg.value == 0 || msg.value >= params.maxLiquidationAmount),\n Errors.LIQUIDATION_AMOUNT_NOT_ENOUGH\n );\n\n vars.isCollateralEnabled =\n collateralReserve.configuration.getLiquidationThreshold() != 0 &&\n userConfig.isUsingAsCollateral(collateralReserve.id) &&\n ICollateralizableERC721(params.xTokenAddress).isUsedAsCollateral(\n params.tokenId\n );\n\n //if collateral isn't enabled as collateral by user, it cannot be liquidated\n require(\n vars.isCollateralEnabled,\n Errors.COLLATERAL_CANNOT_BE_AUCTIONED_OR_LIQUIDATED\n );\n require(params.globalDebt != 0, Errors.GLOBAL_DEBT_IS_ZERO);\n }\n\n /**\n * @notice Validates the health factor of a user.\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param userConfig The state of the user for the specific reserve\n * @param user The user to validate health factor of\n * @param reservesCount The number of available reserves\n * @param oracle The price oracle\n */\n function validateHealthFactor(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap memory userConfig,\n address user,\n uint256 reservesCount,\n address oracle\n ) internal view returns (uint256, bool) {\n (\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n uint256 healthFactor,\n ,\n bool hasZeroLtvCollateral\n ) = GenericLogic.calculateUserAccountData(\n reservesData,\n reservesList,\n DataTypes.CalculateUserAccountDataParams({\n userConfig: userConfig,\n reservesCount: reservesCount,\n user: user,\n oracle: oracle\n })\n );\n\n require(\n healthFactor >= HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n Errors.HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD\n );\n\n return (healthFactor, hasZeroLtvCollateral);\n }\n\n function validateStartAuction(\n DataTypes.UserConfigurationMap storage userConfig,\n DataTypes.ReserveData storage collateralReserve,\n DataTypes.ValidateAuctionParams memory params\n ) internal view {\n ValidateAuctionLocalVars memory vars;\n\n DataTypes.ReserveConfigurationMap\n memory collateralConfiguration = collateralReserve.configuration;\n (\n vars.collateralReserveActive,\n ,\n ,\n vars.collateralReservePaused,\n vars.collateralReserveAssetType\n ) = collateralConfiguration.getFlags();\n\n require(\n vars.collateralReserveAssetType == DataTypes.AssetType.ERC721,\n Errors.INVALID_ASSET_TYPE\n );\n\n require(\n IERC721(params.xTokenAddress).ownerOf(params.tokenId) ==\n params.user,\n Errors.NOT_THE_OWNER\n );\n\n require(vars.collateralReserveActive, Errors.RESERVE_INACTIVE);\n require(!vars.collateralReservePaused, Errors.RESERVE_PAUSED);\n\n require(\n collateralReserve.auctionStrategyAddress != address(0),\n Errors.AUCTION_NOT_ENABLED\n );\n require(\n !IAuctionableERC721(params.xTokenAddress).isAuctioned(\n params.tokenId\n ),\n Errors.AUCTION_ALREADY_STARTED\n );\n\n require(\n params.erc721HealthFactor < HEALTH_FACTOR_LIQUIDATION_THRESHOLD,\n Errors.ERC721_HEALTH_FACTOR_NOT_BELOW_THRESHOLD\n );\n\n vars.isCollateralEnabled =\n collateralConfiguration.getLiquidationThreshold() != 0 &&\n userConfig.isUsingAsCollateral(collateralReserve.id) &&\n ICollateralizableERC721(params.xTokenAddress).isUsedAsCollateral(\n params.tokenId\n );\n\n //if collateral isn't enabled as collateral by user, it cannot be auctioned\n require(\n vars.isCollateralEnabled,\n Errors.COLLATERAL_CANNOT_BE_AUCTIONED_OR_LIQUIDATED\n );\n }\n\n function validateEndAuction(\n DataTypes.ReserveData storage collateralReserve,\n DataTypes.ValidateAuctionParams memory params\n ) internal view {\n ValidateAuctionLocalVars memory vars;\n\n (\n vars.collateralReserveActive,\n ,\n ,\n vars.collateralReservePaused,\n vars.collateralReserveAssetType\n ) = collateralReserve.configuration.getFlags();\n\n require(\n vars.collateralReserveAssetType == DataTypes.AssetType.ERC721,\n Errors.INVALID_ASSET_TYPE\n );\n require(\n IERC721(params.xTokenAddress).ownerOf(params.tokenId) ==\n params.user,\n Errors.NOT_THE_OWNER\n );\n require(vars.collateralReserveActive, Errors.RESERVE_INACTIVE);\n require(!vars.collateralReservePaused, Errors.RESERVE_PAUSED);\n require(\n IAuctionableERC721(params.xTokenAddress).isAuctioned(\n params.tokenId\n ),\n Errors.AUCTION_NOT_STARTED\n );\n\n require(\n params.erc721HealthFactor >= params.auctionRecoveryHealthFactor,\n Errors.ERC721_HEALTH_FACTOR_NOT_ABOVE_THRESHOLD\n );\n }\n\n /**\n * @notice Validates the health factor of a user and the ltv of the asset being withdrawn.\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param userConfig The state of the user for the specific reserve\n * @param asset The asset for which the ltv will be validated\n * @param from The user from which the xTokens are being transferred\n * @param reservesCount The number of available reserves\n * @param oracle The price oracle\n */\n function validateHFAndLtvERC20(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap memory userConfig,\n address asset,\n address from,\n uint256 reservesCount,\n address oracle\n ) internal view {\n DataTypes.ReserveData storage reserve = reservesData[asset];\n\n (, bool hasZeroLtvCollateral) = validateHealthFactor(\n reservesData,\n reservesList,\n userConfig,\n from,\n reservesCount,\n oracle\n );\n\n require(\n !hasZeroLtvCollateral || reserve.configuration.getLtv() == 0,\n Errors.LTV_VALIDATION_FAILED\n );\n }\n\n /**\n * @notice Validates the health factor of a user and the ltv of the erc721 asset being withdrawn.\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param userConfig The state of the user for the specific reserve\n * @param asset The asset for which the ltv will be validated\n * @param tokenIds The asset tokenIds for which the ltv will be validated\n * @param from The user from which the xTokens are being transferred\n * @param reservesCount The number of available reserves\n * @param oracle The price oracle\n */\n function validateHFAndLtvERC721(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.UserConfigurationMap memory userConfig,\n address asset,\n uint256[] memory tokenIds,\n address from,\n uint256 reservesCount,\n address oracle\n ) internal view {\n DataTypes.ReserveData storage reserve = reservesData[asset];\n\n (, bool hasZeroLtvCollateral) = validateHealthFactor(\n reservesData,\n reservesList,\n userConfig,\n from,\n reservesCount,\n oracle\n );\n\n if (hasZeroLtvCollateral) {\n INToken nToken = INToken(reserve.xTokenAddress);\n if (nToken.getXTokenType() == XTokenType.NTokenUniswapV3) {\n for (uint256 index = 0; index < tokenIds.length; index++) {\n (uint256 assetLTV, ) = GenericLogic.getLtvAndLTForUniswapV3(\n reservesData,\n asset,\n tokenIds[index],\n reserve.configuration.getLtv(),\n 0\n );\n require(assetLTV == 0, Errors.LTV_VALIDATION_FAILED);\n }\n } else {\n require(\n reserve.configuration.getLtv() == 0,\n Errors.LTV_VALIDATION_FAILED\n );\n }\n }\n }\n\n /**\n * @notice Validates a transfer action.\n * @param reserve The reserve object\n */\n function validateTransferERC20(DataTypes.ReserveData storage reserve)\n internal\n view\n {\n require(!reserve.configuration.getPaused(), Errors.RESERVE_PAUSED);\n }\n\n /**\n * @notice Validates a transfer action.\n * @param reserve The reserve object\n */\n function validateTransferERC721(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.ReserveData storage reserve,\n address asset,\n uint256 tokenId\n ) internal view {\n require(!reserve.configuration.getPaused(), Errors.RESERVE_PAUSED);\n INToken nToken = INToken(reserve.xTokenAddress);\n if (nToken.getXTokenType() == XTokenType.NTokenUniswapV3) {\n ValidationLogic.validateForUniswapV3(\n reservesData,\n asset,\n tokenId,\n false,\n true,\n false\n );\n }\n }\n\n /**\n * @notice Validates a drop reserve action.\n * @param reservesList The addresses of all the active reserves\n * @param reserve The reserve object\n * @param asset The address of the reserve's underlying asset\n **/\n function validateDropReserve(\n mapping(uint256 => address) storage reservesList,\n DataTypes.ReserveData storage reserve,\n address asset\n ) internal view {\n require(asset != address(0), Errors.ZERO_ADDRESS_NOT_VALID);\n require(\n reserve.id != 0 || reservesList[0] == asset,\n Errors.ASSET_NOT_LISTED\n );\n require(\n IToken(reserve.variableDebtTokenAddress).totalSupply() == 0,\n Errors.VARIABLE_DEBT_SUPPLY_NOT_ZERO\n );\n require(\n IToken(reserve.xTokenAddress).totalSupply() == 0,\n Errors.XTOKEN_SUPPLY_NOT_ZERO\n );\n }\n\n /**\n * @notice Validates a flash claim.\n * @param ps The pool storage\n * @param params The flash claim params\n */\n function validateFlashClaim(\n DataTypes.PoolStorage storage ps,\n DataTypes.ExecuteFlashClaimParams memory params\n ) internal view {\n DataTypes.ReserveData storage reserve = ps._reserves[params.nftAsset];\n require(\n reserve.configuration.getAssetType() == DataTypes.AssetType.ERC721,\n Errors.INVALID_ASSET_TYPE\n );\n require(\n params.receiverAddress != address(0),\n Errors.ZERO_ADDRESS_NOT_VALID\n );\n\n INToken nToken = INToken(reserve.xTokenAddress);\n XTokenType tokenType = nToken.getXTokenType();\n require(\n tokenType != XTokenType.NTokenUniswapV3,\n Errors.UNIV3_NOT_ALLOWED\n );\n\n // need check sApe status when flash claim for bayc or mayc\n if (\n tokenType == XTokenType.NTokenBAYC ||\n tokenType == XTokenType.NTokenMAYC\n ) {\n DataTypes.ReserveData storage sApeReserve = ps._reserves[\n DataTypes.SApeAddress\n ];\n\n (bool isActive, , , bool isPaused, ) = sApeReserve\n .configuration\n .getFlags();\n\n require(isActive, Errors.RESERVE_INACTIVE);\n require(!isPaused, Errors.RESERVE_PAUSED);\n }\n\n // only token owner can do flash claim\n for (uint256 i = 0; i < params.nftTokenIds.length; i++) {\n require(\n nToken.ownerOf(params.nftTokenIds[i]) == msg.sender,\n Errors.NOT_THE_OWNER\n );\n }\n }\n\n /**\n * @notice Validates a flashloan action.\n * @param reserve The state of the reserve\n */\n function validateFlashloanSimple(DataTypes.ReserveData storage reserve)\n internal\n view\n {\n (\n bool isActive,\n ,\n ,\n bool isPaused,\n DataTypes.AssetType assetType\n ) = reserve.configuration.getFlags();\n require(isActive, Errors.RESERVE_INACTIVE);\n require(!isPaused, Errors.RESERVE_PAUSED);\n require(\n assetType == DataTypes.AssetType.ERC20,\n Errors.INVALID_ASSET_TYPE\n );\n }\n\n function validateBuyWithCredit(\n DataTypes.ExecuteMarketplaceParams memory params\n ) internal pure {\n require(!params.marketplace.paused, Errors.MARKETPLACE_PAUSED);\n }\n\n function validateAcceptBidWithCredit(\n DataTypes.ExecuteMarketplaceParams memory params\n ) internal view {\n require(!params.marketplace.paused, Errors.MARKETPLACE_PAUSED);\n require(\n keccak256(abi.encodePacked(params.orderInfo.id)) ==\n keccak256(abi.encodePacked(params.credit.orderId)),\n Errors.CREDIT_DOES_NOT_MATCH_ORDER\n );\n require(\n verifyCreditSignature(\n params.credit,\n params.orderInfo.maker,\n params.credit.v,\n params.credit.r,\n params.credit.s\n ),\n Errors.INVALID_CREDIT_SIGNATURE\n );\n }\n\n function verifyCreditSignature(\n DataTypes.Credit memory credit,\n address signer,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) private view returns (bool) {\n return\n SignatureChecker.verify(\n hashCredit(credit),\n signer,\n v,\n r,\n s,\n getDomainSeparator()\n );\n }\n\n function hashCredit(DataTypes.Credit memory credit)\n private\n pure\n returns (bytes32)\n {\n bytes32 typeHash = keccak256(\n abi.encodePacked(\n \"Credit(address token,uint256 amount,bytes orderId)\"\n )\n );\n\n // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#definition-of-encodedata\n return\n keccak256(\n abi.encode(\n typeHash,\n credit.token,\n credit.amount,\n keccak256(abi.encodePacked(credit.orderId))\n )\n );\n }\n\n function getDomainSeparator() internal view returns (bytes32) {\n return\n keccak256(\n abi.encode(\n 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, // keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\")\n 0x88d989289235fb06c18e3c2f7ea914f41f773e86fb0073d632539f566f4df353, // keccak256(\"ParaSpace\")\n 0x722c0e0c80487266e8c6a45e3a1a803aab23378a9c32e6ebe029d4fad7bfc965, // keccak256(bytes(\"1.1\")),\n block.chainid,\n address(this)\n )\n );\n }\n\n struct ValidateForUniswapV3LocalVars {\n bool token0IsActive;\n bool token0IsFrozen;\n bool token0IsPaused;\n bool token1IsActive;\n bool token1IsFrozen;\n bool token1IsPaused;\n }\n\n function validateForUniswapV3(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n address asset,\n uint256 tokenId,\n bool checkActive,\n bool checkNotPaused,\n bool checkNotFrozen\n ) internal view {\n (\n ,\n ,\n address token0,\n address token1,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n\n ) = INonfungiblePositionManager(asset).positions(tokenId);\n\n ValidateForUniswapV3LocalVars memory vars;\n (\n vars.token0IsActive,\n vars.token0IsFrozen,\n ,\n vars.token0IsPaused,\n\n ) = reservesData[token0].configuration.getFlags();\n\n (\n vars.token1IsActive,\n vars.token1IsFrozen,\n ,\n vars.token1IsPaused,\n\n ) = reservesData[token1].configuration.getFlags();\n\n if (checkActive) {\n require(\n vars.token0IsActive && vars.token1IsActive,\n Errors.RESERVE_INACTIVE\n );\n }\n if (checkNotPaused) {\n require(\n !vars.token0IsPaused && !vars.token1IsPaused,\n Errors.RESERVE_PAUSED\n );\n }\n if (checkNotFrozen) {\n require(\n !vars.token0IsFrozen && !vars.token1IsFrozen,\n Errors.RESERVE_FROZEN\n );\n }\n }\n}\n" }, "contracts/protocol/libraries/logic/GenericLogic.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {IERC20} from \"../../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {IERC721Enumerable} from \"../../../dependencies/openzeppelin/contracts/IERC721Enumerable.sol\";\nimport {Math} from \"../../../dependencies/openzeppelin/contracts/Math.sol\";\nimport {IScaledBalanceToken} from \"../../../interfaces/IScaledBalanceToken.sol\";\nimport {INToken} from \"../../../interfaces/INToken.sol\";\nimport {ICollateralizableERC721} from \"../../../interfaces/ICollateralizableERC721.sol\";\nimport {IPriceOracleGetter} from \"../../../interfaces/IPriceOracleGetter.sol\";\nimport {ReserveConfiguration} from \"../configuration/ReserveConfiguration.sol\";\nimport {UserConfiguration} from \"../configuration/UserConfiguration.sol\";\nimport {PercentageMath} from \"../math/PercentageMath.sol\";\nimport {WadRayMath} from \"../math/WadRayMath.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\nimport {ReserveLogic} from \"./ReserveLogic.sol\";\nimport {INonfungiblePositionManager} from \"../../../dependencies/uniswap/INonfungiblePositionManager.sol\";\nimport {XTokenType} from \"../../../interfaces/IXTokenType.sol\";\n\n/**\n * @title GenericLogic library\n *\n * @notice Implements protocol-level logic to calculate and validate the state of a user\n */\nlibrary GenericLogic {\n using ReserveLogic for DataTypes.ReserveData;\n using WadRayMath for uint256;\n using PercentageMath for uint256;\n using ReserveConfiguration for DataTypes.ReserveConfigurationMap;\n using UserConfiguration for DataTypes.UserConfigurationMap;\n\n struct CalculateUserAccountDataVars {\n uint256 assetPrice;\n uint256 assetUnit;\n DataTypes.ReserveConfigurationMap reserveConfiguration;\n uint256 userBalanceInBaseCurrency;\n uint256 decimals;\n uint256 ltv;\n uint256 liquidationThreshold;\n uint256 liquidationBonus;\n uint256 i;\n uint256 healthFactor;\n uint256 erc721HealthFactor;\n uint256 totalERC721CollateralInBaseCurrency;\n uint256 payableDebtByERC20Assets;\n uint256 totalCollateralInBaseCurrency;\n uint256 totalDebtInBaseCurrency;\n uint256 avgLtv;\n uint256 avgLiquidationThreshold;\n uint256 avgERC721LiquidationThreshold;\n address currentReserveAddress;\n bool hasZeroLtvCollateral;\n address xTokenAddress;\n XTokenType xTokenType;\n }\n\n /**\n * @notice Calculates the user data across the reserves.\n * @dev It includes the total liquidity/collateral/borrow balances in the base currency used by the price feed,\n * the average Loan To Value, the average Liquidation Ratio, and the Health factor.\n * @param reservesData The state of all the reserves\n * @param reservesList The addresses of all the active reserves\n * @param params Additional parameters needed for the calculation\n * @return The total collateral of the user in the base currency used by the price feed\n * @return The total ERC721 collateral of the user in the base currency used by the price feed\n * @return The total debt of the user in the base currency used by the price feed\n * @return The average ltv of the user\n * @return The average liquidation threshold of the user\n * @return The payable debt by ERC20 assets\n * @return The health factor of the user\n * @return The ERC721 health factor of the user\n * @return True if the ltv is zero, false otherwise\n **/\n function calculateUserAccountData(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n mapping(uint256 => address) storage reservesList,\n DataTypes.CalculateUserAccountDataParams memory params\n )\n internal\n view\n returns (\n uint256,\n uint256,\n uint256,\n uint256,\n uint256,\n uint256,\n uint256,\n uint256,\n uint256,\n bool\n )\n {\n if (params.userConfig.isEmpty()) {\n return (\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n 0,\n type(uint256).max,\n type(uint256).max,\n false\n );\n }\n\n CalculateUserAccountDataVars memory vars;\n\n while (vars.i < params.reservesCount) {\n if (!params.userConfig.isUsingAsCollateralOrBorrowing(vars.i)) {\n unchecked {\n ++vars.i;\n }\n continue;\n }\n\n vars.currentReserveAddress = reservesList[vars.i];\n\n if (vars.currentReserveAddress == address(0)) {\n unchecked {\n ++vars.i;\n }\n continue;\n }\n\n DataTypes.ReserveData storage currentReserve = reservesData[\n vars.currentReserveAddress\n ];\n\n vars.reserveConfiguration = currentReserve.configuration;\n\n (\n vars.ltv,\n vars.liquidationThreshold,\n vars.liquidationBonus,\n vars.decimals,\n\n ) = currentReserve.configuration.getParams();\n\n unchecked {\n vars.assetUnit = 10**vars.decimals;\n }\n\n vars.xTokenAddress = currentReserve.xTokenAddress;\n\n if (\n vars.reserveConfiguration.getAssetType() ==\n DataTypes.AssetType.ERC20\n ) {\n vars.assetPrice = _getAssetPrice(\n params.oracle,\n vars.currentReserveAddress\n );\n\n if (\n (vars.liquidationThreshold != 0) &&\n params.userConfig.isUsingAsCollateral(vars.i)\n ) {\n vars.userBalanceInBaseCurrency = _getUserBalanceForERC20(\n params.user,\n currentReserve,\n vars.xTokenAddress,\n vars.assetUnit,\n vars.assetPrice\n );\n\n vars.payableDebtByERC20Assets += vars\n .userBalanceInBaseCurrency\n .percentDiv(vars.liquidationBonus);\n\n vars.liquidationThreshold =\n vars.userBalanceInBaseCurrency *\n (vars.liquidationThreshold);\n vars.avgLtv += vars.userBalanceInBaseCurrency * vars.ltv;\n\n vars.totalCollateralInBaseCurrency += vars\n .userBalanceInBaseCurrency;\n\n if (vars.ltv == 0) {\n vars.hasZeroLtvCollateral = true;\n }\n\n vars.avgLiquidationThreshold += vars.liquidationThreshold;\n }\n\n if (params.userConfig.isBorrowing(vars.i)) {\n vars.totalDebtInBaseCurrency += _getUserDebtInBaseCurrency(\n params.user,\n currentReserve,\n vars.assetPrice,\n vars.assetUnit\n );\n }\n } else {\n if (\n (vars.liquidationThreshold != 0) &&\n params.userConfig.isUsingAsCollateral(vars.i)\n ) {\n vars.xTokenType = INToken(vars.xTokenAddress)\n .getXTokenType();\n if (vars.xTokenType == XTokenType.NTokenUniswapV3) {\n (\n vars.userBalanceInBaseCurrency,\n vars.ltv,\n vars.liquidationThreshold\n ) = _getUserBalanceForUniswapV3(\n reservesData,\n params,\n vars\n );\n } else {\n vars\n .userBalanceInBaseCurrency = _getUserBalanceForERC721(\n params,\n vars\n );\n\n vars.liquidationThreshold =\n vars.userBalanceInBaseCurrency *\n vars.liquidationThreshold;\n\n if (vars.ltv == 0) {\n vars.hasZeroLtvCollateral = true;\n }\n\n vars.ltv = vars.userBalanceInBaseCurrency * vars.ltv;\n }\n\n vars.avgERC721LiquidationThreshold += vars\n .liquidationThreshold;\n vars.totalERC721CollateralInBaseCurrency += vars\n .userBalanceInBaseCurrency;\n vars.totalCollateralInBaseCurrency += vars\n .userBalanceInBaseCurrency;\n vars.avgLtv += vars.ltv;\n vars.avgLiquidationThreshold += vars.liquidationThreshold;\n }\n }\n\n unchecked {\n ++vars.i;\n }\n }\n\n unchecked {\n vars.avgLtv = vars.totalCollateralInBaseCurrency != 0\n ? vars.avgLtv / vars.totalCollateralInBaseCurrency\n : 0;\n vars.avgLiquidationThreshold = vars.totalCollateralInBaseCurrency !=\n 0\n ? vars.avgLiquidationThreshold /\n vars.totalCollateralInBaseCurrency\n : 0;\n\n vars.avgERC721LiquidationThreshold = vars\n .totalERC721CollateralInBaseCurrency != 0\n ? vars.avgERC721LiquidationThreshold /\n vars.totalERC721CollateralInBaseCurrency\n : 0;\n }\n\n vars.healthFactor = (vars.totalDebtInBaseCurrency == 0)\n ? type(uint256).max\n : (\n vars.totalCollateralInBaseCurrency.percentMul(\n vars.avgLiquidationThreshold\n )\n ).wadDiv(vars.totalDebtInBaseCurrency);\n\n vars.erc721HealthFactor = (vars.totalDebtInBaseCurrency == 0 ||\n vars.payableDebtByERC20Assets >= vars.totalDebtInBaseCurrency)\n ? type(uint256).max\n : (\n vars.totalERC721CollateralInBaseCurrency.percentMul(\n vars.avgERC721LiquidationThreshold\n )\n ).wadDiv(\n vars.totalDebtInBaseCurrency - vars.payableDebtByERC20Assets\n );\n\n return (\n vars.totalCollateralInBaseCurrency,\n vars.totalERC721CollateralInBaseCurrency,\n vars.totalDebtInBaseCurrency,\n vars.avgLtv,\n vars.avgLiquidationThreshold,\n vars.avgERC721LiquidationThreshold,\n vars.payableDebtByERC20Assets,\n vars.healthFactor,\n vars.erc721HealthFactor,\n vars.hasZeroLtvCollateral\n );\n }\n\n /**\n * @notice Calculates the maximum amount that can be borrowed depending on the available collateral, the total debt\n * and the average Loan To Value\n * @param totalCollateralInBaseCurrency The total collateral in the base currency used by the price feed\n * @param totalDebtInBaseCurrency The total borrow balance in the base currency used by the price feed\n * @param ltv The average loan to value\n * @return The amount available to borrow in the base currency of the used by the price feed\n **/\n function calculateAvailableBorrows(\n uint256 totalCollateralInBaseCurrency,\n uint256 totalDebtInBaseCurrency,\n uint256 ltv\n ) internal pure returns (uint256) {\n uint256 availableBorrowsInBaseCurrency = totalCollateralInBaseCurrency\n .percentMul(ltv);\n\n if (availableBorrowsInBaseCurrency < totalDebtInBaseCurrency) {\n return 0;\n }\n\n availableBorrowsInBaseCurrency =\n availableBorrowsInBaseCurrency -\n totalDebtInBaseCurrency;\n return availableBorrowsInBaseCurrency;\n }\n\n /**\n * @notice Calculates total debt of the user in the based currency used to normalize the values of the assets\n * @dev This fetches the `balanceOf` of the stable and variable debt tokens for the user. For gas reasons, the\n * variable debt balance is calculated by fetching `scaledBalancesOf` normalized debt, which is cheaper than\n * fetching `balanceOf`\n * @param user The address of the user\n * @param reserve The data of the reserve for which the total debt of the user is being calculated\n * @param assetPrice The price of the asset for which the total debt of the user is being calculated\n * @param assetUnit The value representing one full unit of the asset (10^decimals)\n * @return The total debt of the user normalized to the base currency\n **/\n function _getUserDebtInBaseCurrency(\n address user,\n DataTypes.ReserveData storage reserve,\n uint256 assetPrice,\n uint256 assetUnit\n ) private view returns (uint256) {\n // fetching variable debt\n uint256 userTotalDebt = IScaledBalanceToken(\n reserve.variableDebtTokenAddress\n ).scaledBalanceOf(user);\n if (userTotalDebt != 0) {\n userTotalDebt = userTotalDebt.rayMul(reserve.getNormalizedDebt());\n userTotalDebt = assetPrice * userTotalDebt;\n\n unchecked {\n return userTotalDebt / assetUnit;\n }\n } else {\n return 0;\n }\n }\n\n /**\n * @notice Calculates total xToken balance of the user in the based currency used by the price oracle\n * @dev For gas reasons, the xToken balance is calculated by fetching `scaledBalancesOf` normalized debt, which\n * is cheaper than fetching `balanceOf`\n * @return totalValue The total xToken balance of the user normalized to the base currency of the price oracle\n **/\n function _getUserBalanceForERC721(\n DataTypes.CalculateUserAccountDataParams memory params,\n CalculateUserAccountDataVars memory vars\n ) private view returns (uint256 totalValue) {\n INToken nToken = INToken(vars.xTokenAddress);\n bool isAtomicPrice = nToken.getAtomicPricingConfig();\n if (isAtomicPrice) {\n uint256 totalBalance = nToken.balanceOf(params.user);\n\n for (uint256 index = 0; index < totalBalance; index++) {\n uint256 tokenId = nToken.tokenOfOwnerByIndex(\n params.user,\n index\n );\n if (\n ICollateralizableERC721(vars.xTokenAddress)\n .isUsedAsCollateral(tokenId)\n ) {\n totalValue += _getTokenPrice(\n params.oracle,\n vars.currentReserveAddress,\n tokenId\n );\n }\n }\n } else {\n uint256 assetPrice = _getAssetPrice(\n params.oracle,\n vars.currentReserveAddress\n );\n totalValue =\n ICollateralizableERC721(vars.xTokenAddress)\n .collateralizedBalanceOf(params.user) *\n assetPrice;\n }\n }\n\n function getLtvAndLTForUniswapV3(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n address uniswapV3Manager,\n uint256 tokenId,\n uint256 collectionLTV,\n uint256 collectionLiquidationThreshold\n ) internal view returns (uint256 ltv, uint256 liquidationThreshold) {\n (\n ,\n ,\n address token0,\n address token1,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n\n ) = INonfungiblePositionManager(uniswapV3Manager).positions(tokenId);\n\n DataTypes.ReserveConfigurationMap memory token0Configs = reservesData[\n token0\n ].configuration;\n DataTypes.ReserveConfigurationMap memory token1Configs = reservesData[\n token1\n ].configuration;\n\n (\n uint256 token0Ltv,\n uint256 token0LiquidationThreshold,\n ,\n ,\n\n ) = token0Configs.getParams();\n (\n uint256 token1Ltv,\n uint256 token1LiquidationThreshold,\n ,\n ,\n\n ) = token1Configs.getParams();\n\n ltv = Math.min(Math.min(token0Ltv, token1Ltv), collectionLTV);\n liquidationThreshold = Math.min(\n Math.min(token0LiquidationThreshold, token1LiquidationThreshold),\n collectionLiquidationThreshold\n );\n }\n\n function _getUserBalanceForUniswapV3(\n mapping(address => DataTypes.ReserveData) storage reservesData,\n DataTypes.CalculateUserAccountDataParams memory params,\n CalculateUserAccountDataVars memory vars\n )\n private\n view\n returns (\n uint256 totalValue,\n uint256 totalLTV,\n uint256 totalLiquidationThreshold\n )\n {\n uint256 totalBalance = INToken(vars.xTokenAddress).balanceOf(\n params.user\n );\n for (uint256 index = 0; index < totalBalance; index++) {\n uint256 tokenId = IERC721Enumerable(vars.xTokenAddress)\n .tokenOfOwnerByIndex(params.user, index);\n if (\n ICollateralizableERC721(vars.xTokenAddress).isUsedAsCollateral(\n tokenId\n )\n ) {\n uint256 tokenPrice = _getTokenPrice(\n params.oracle,\n vars.currentReserveAddress,\n tokenId\n );\n totalValue += tokenPrice;\n\n (\n uint256 tmpLTV,\n uint256 tmpLiquidationThreshold\n ) = getLtvAndLTForUniswapV3(\n reservesData,\n vars.currentReserveAddress,\n tokenId,\n vars.ltv,\n vars.liquidationThreshold\n );\n\n if (tmpLTV == 0) {\n vars.hasZeroLtvCollateral = true;\n }\n\n totalLTV += tmpLTV * tokenPrice;\n totalLiquidationThreshold +=\n tmpLiquidationThreshold *\n tokenPrice;\n }\n }\n }\n\n /**\n * @notice Calculates total xToken balance of the user in the based currency used by the price oracle\n * @dev For gas reasons, the xToken balance is calculated by fetching `scaledBalancesOf` normalized debt, which\n * is cheaper than fetching `balanceOf`\n * @param user The address of the user\n * @param assetUnit The value representing one full unit of the asset (10^decimals)\n * @return The total xToken balance of the user normalized to the base currency of the price oracle\n **/\n function _getUserBalanceForERC20(\n address user,\n DataTypes.ReserveData storage reserve,\n address xTokenAddress,\n uint256 assetUnit,\n uint256 assetPrice\n ) private view returns (uint256) {\n uint256 balance;\n\n uint256 normalizedIncome = reserve.getNormalizedIncome();\n balance =\n (\n IScaledBalanceToken(xTokenAddress).scaledBalanceOf(user).rayMul(\n normalizedIncome\n )\n ) *\n assetPrice;\n\n unchecked {\n return (balance / assetUnit);\n }\n }\n\n function _getAssetPrice(address oracle, address currentReserveAddress)\n internal\n view\n returns (uint256)\n {\n return IPriceOracleGetter(oracle).getAssetPrice(currentReserveAddress);\n }\n\n function _getTokenPrice(\n address oracle,\n address currentReserveAddress,\n uint256 tokenId\n ) internal view returns (uint256) {\n return\n IPriceOracleGetter(oracle).getTokenPrice(\n currentReserveAddress,\n tokenId\n );\n }\n}\n" }, "contracts/interfaces/IInitializablePToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IRewardController} from \"./IRewardController.sol\";\nimport {IPool} from \"./IPool.sol\";\n\n/**\n * @title IInitializablePToken\n *\n * @notice Interface for the initialize function on PToken\n **/\ninterface IInitializablePToken {\n /**\n * @dev Emitted when an pToken is initialized\n * @param underlyingAsset The address of the underlying asset\n * @param pool The address of the associated pool\n * @param treasury The address of the treasury\n * @param incentivesController The address of the incentives controller for this pToken\n * @param pTokenDecimals The decimals of the underlying\n * @param pTokenName The name of the pToken\n * @param pTokenSymbol The symbol of the pToken\n * @param params A set of encoded parameters for additional initialization\n **/\n event Initialized(\n address indexed underlyingAsset,\n address indexed pool,\n address treasury,\n address incentivesController,\n uint8 pTokenDecimals,\n string pTokenName,\n string pTokenSymbol,\n bytes params\n );\n\n /**\n * @notice Initializes the pToken\n * @param pool The pool contract that is initializing this contract\n * @param treasury The address of the ParaSpace treasury, receiving the fees on this pToken\n * @param underlyingAsset The address of the underlying asset of this pToken (E.g. WETH for pWETH)\n * @param incentivesController The smart contract managing potential incentives distribution\n * @param pTokenDecimals The decimals of the pToken, same as the underlying asset's\n * @param pTokenName The name of the pToken\n * @param pTokenSymbol The symbol of the pToken\n * @param params A set of encoded parameters for additional initialization\n */\n function initialize(\n IPool pool,\n address treasury,\n address underlyingAsset,\n IRewardController incentivesController,\n uint8 pTokenDecimals,\n string calldata pTokenName,\n string calldata pTokenSymbol,\n bytes calldata params\n ) external;\n}\n" }, "contracts/interfaces/IPriceOracleGetter.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title IPriceOracleGetter\n *\n * @notice Interface for the ParaSpace price oracle.\n **/\ninterface IPriceOracleGetter {\n /**\n * @notice Returns the base currency address\n * @dev Address 0x0 is reserved for USD as base currency.\n * @return Returns the base currency address.\n **/\n function BASE_CURRENCY() external view returns (address);\n\n /**\n * @notice Returns the base currency unit\n * @dev 1 ether for ETH, 1e8 for USD.\n * @return Returns the base currency unit.\n **/\n function BASE_CURRENCY_UNIT() external view returns (uint256);\n\n /**\n * @notice Returns the asset price in the base currency\n * @param asset The address of the asset\n * @return The price of the asset\n **/\n function getAssetPrice(address asset) external view returns (uint256);\n\n /**\n * @notice Returns the price of a token\n * @param asset the asset address\n * @param tokenId the token id\n * @return The price of the given token\n */\n function getTokenPrice(address asset, uint256 tokenId)\n external\n view\n returns (uint256);\n}\n" }, "contracts/interfaces/ICollateralizableERC721.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\n/**\n * @title ICollateralizableERC721\n * @author Parallel\n * @notice Defines the basic interface for an CollateralizableERC721.\n **/\ninterface ICollateralizableERC721 {\n /**\n * @dev get the collateralized balance of a specific user\n */\n function collateralizedBalanceOf(address user)\n external\n view\n returns (uint256);\n\n /**\n * @dev get the the collateral configuration of a specific token\n */\n function isUsedAsCollateral(uint256 tokenId) external view returns (bool);\n\n /**\n * @dev changes the collateral state/config of a token\n * @return if the state has changed\n */\n function setIsUsedAsCollateral(\n uint256 tokenId,\n bool useAsCollateral,\n address sender\n ) external returns (bool);\n\n /**\n * @dev the ids of the token want to change the collateral state\n * @return uint256 (user's old collateralized balance), uint256 (user's new collateralized balance)\n */\n function batchSetIsUsedAsCollateral(\n uint256[] calldata tokenIds,\n bool useAsCollateral,\n address sender\n ) external returns (uint256, uint256);\n}\n" }, "contracts/interfaces/INTokenApeStaking.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport \"../dependencies/yoga-labs/ApeCoinStaking.sol\";\nimport \"./INToken.sol\";\n\ninterface INTokenApeStaking {\n function getBAKC() external view returns (IERC721);\n\n function getApeStaking() external view returns (ApeCoinStaking);\n\n function depositApeCoin(ApeCoinStaking.SingleNft[] calldata _nfts) external;\n\n function claimApeCoin(uint256[] calldata _nfts, address _recipient)\n external;\n\n function withdrawApeCoin(\n ApeCoinStaking.SingleNft[] calldata _nfts,\n address _recipient\n ) external;\n\n function depositBAKC(\n ApeCoinStaking.PairNftDepositWithAmount[] calldata _nftPairs\n ) external;\n\n function claimBAKC(\n ApeCoinStaking.PairNft[] calldata _nftPairs,\n address _recipient\n ) external;\n\n function withdrawBAKC(\n ApeCoinStaking.PairNftWithdrawWithAmount[] memory _nftPairs,\n address _apeRecipient\n ) external;\n\n function unstakePositionAndRepay(uint256 tokenId, address unstaker)\n external;\n\n function getUserApeStakingAmount(address user)\n external\n view\n returns (uint256);\n}\n" }, "contracts/interfaces/IPriceOracleSentinel.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\nimport {IPoolAddressesProvider} from \"./IPoolAddressesProvider.sol\";\n\n/**\n * @title IPriceOracleSentinel\n *\n * @notice Defines the basic interface for the PriceOracleSentinel\n */\ninterface IPriceOracleSentinel {\n /**\n * @dev Emitted after the sequencer oracle is updated\n * @param newSequencerOracle The new sequencer oracle\n */\n event SequencerOracleUpdated(address newSequencerOracle);\n\n /**\n * @dev Emitted after the grace period is updated\n * @param newGracePeriod The new grace period value\n */\n event GracePeriodUpdated(uint256 newGracePeriod);\n\n /**\n * @notice Returns the PoolAddressesProvider\n * @return The address of the PoolAddressesProvider contract\n */\n function ADDRESSES_PROVIDER()\n external\n view\n returns (IPoolAddressesProvider);\n\n /**\n * @notice Returns true if the `borrow` operation is allowed.\n * @dev Operation not allowed when PriceOracle is down or grace period not passed.\n * @return True if the `borrow` operation is allowed, false otherwise.\n */\n function isBorrowAllowed() external view returns (bool);\n\n /**\n * @notice Returns true if the `liquidation` operation is allowed.\n * @dev Operation not allowed when PriceOracle is down or grace period not passed.\n * @return True if the `liquidation` operation is allowed, false otherwise.\n */\n function isLiquidationAllowed() external view returns (bool);\n\n /**\n * @notice Updates the address of the sequencer oracle\n * @param newSequencerOracle The address of the new Sequencer Oracle to use\n */\n function setSequencerOracle(address newSequencerOracle) external;\n\n /**\n * @notice Updates the duration of the grace period\n * @param newGracePeriod The value of the new grace period duration\n */\n function setGracePeriod(uint256 newGracePeriod) external;\n\n /**\n * @notice Returns the SequencerOracle\n * @return The address of the sequencer oracle contract\n */\n function getSequencerOracle() external view returns (address);\n\n /**\n * @notice Returns the grace period\n * @return The duration of the grace period\n */\n function getGracePeriod() external view returns (uint256);\n}\n" }, "contracts/interfaces/IToken.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\ninterface IToken {\n function balanceOf(address) external view returns (uint256);\n\n function totalSupply() external view returns (uint256);\n}\n" }, "contracts/dependencies/uniswap/INonfungiblePositionManager.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport \"../openzeppelin/contracts/IERC721Metadata.sol\";\nimport \"../openzeppelin/contracts/IERC721Enumerable.sol\";\n\nimport \"./IPoolInitializer.sol\";\nimport \"./IERC721Permit.sol\";\nimport \"./IPeripheryPayments.sol\";\nimport \"./IPeripheryImmutableState.sol\";\nimport \"./PoolAddress.sol\";\n\n/// @title Non-fungible token for positions\n/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred\n/// and authorized.\ninterface INonfungiblePositionManager is\n IPoolInitializer,\n IPeripheryPayments,\n IPeripheryImmutableState,\n IERC721Metadata,\n IERC721Enumerable,\n IERC721Permit\n{\n /// @notice Emitted when liquidity is increased for a position NFT\n /// @dev Also emitted when a token is minted\n /// @param tokenId The ID of the token for which liquidity was increased\n /// @param liquidity The amount by which liquidity for the NFT position was increased\n /// @param amount0 The amount of token0 that was paid for the increase in liquidity\n /// @param amount1 The amount of token1 that was paid for the increase in liquidity\n event IncreaseLiquidity(\n uint256 indexed tokenId,\n uint128 liquidity,\n uint256 amount0,\n uint256 amount1\n );\n /// @notice Emitted when liquidity is decreased for a position NFT\n /// @param tokenId The ID of the token for which liquidity was decreased\n /// @param liquidity The amount by which liquidity for the NFT position was decreased\n /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity\n /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity\n event DecreaseLiquidity(\n uint256 indexed tokenId,\n uint128 liquidity,\n uint256 amount0,\n uint256 amount1\n );\n /// @notice Emitted when tokens are collected for a position NFT\n /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior\n /// @param tokenId The ID of the token for which underlying tokens were collected\n /// @param recipient The address of the account that received the collected tokens\n /// @param amount0 The amount of token0 owed to the position that was collected\n /// @param amount1 The amount of token1 owed to the position that was collected\n event Collect(\n uint256 indexed tokenId,\n address recipient,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Returns the position information associated with a given token ID.\n /// @dev Throws if the token ID is not valid.\n /// @param tokenId The ID of the token that represents the position\n /// @return nonce The nonce for permits\n /// @return operator The address that is approved for spending\n /// @return token0 The address of the token0 for a specific pool\n /// @return token1 The address of the token1 for a specific pool\n /// @return fee The fee associated with the pool\n /// @return tickLower The lower end of the tick range for the position\n /// @return tickUpper The higher end of the tick range for the position\n /// @return liquidity The liquidity of the position\n /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position\n /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position\n /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation\n /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation\n function positions(uint256 tokenId)\n external\n view\n returns (\n uint96 nonce,\n address operator,\n address token0,\n address token1,\n uint24 fee,\n int24 tickLower,\n int24 tickUpper,\n uint128 liquidity,\n uint256 feeGrowthInside0LastX128,\n uint256 feeGrowthInside1LastX128,\n uint128 tokensOwed0,\n uint128 tokensOwed1\n );\n\n struct MintParams {\n address token0;\n address token1;\n uint24 fee;\n int24 tickLower;\n int24 tickUpper;\n uint256 amount0Desired;\n uint256 amount1Desired;\n uint256 amount0Min;\n uint256 amount1Min;\n address recipient;\n uint256 deadline;\n }\n\n /// @notice Creates a new position wrapped in a NFT\n /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized\n /// a method does not exist, i.e. the pool is assumed to be initialized.\n /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata\n /// @return tokenId The ID of the token that represents the minted position\n /// @return liquidity The amount of liquidity for this position\n /// @return amount0 The amount of token0\n /// @return amount1 The amount of token1\n function mint(MintParams calldata params)\n external\n payable\n returns (\n uint256 tokenId,\n uint128 liquidity,\n uint256 amount0,\n uint256 amount1\n );\n\n struct IncreaseLiquidityParams {\n uint256 tokenId;\n uint256 amount0Desired;\n uint256 amount1Desired;\n uint256 amount0Min;\n uint256 amount1Min;\n uint256 deadline;\n }\n\n /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`\n /// @param params tokenId The ID of the token for which liquidity is being increased,\n /// amount0Desired The desired amount of token0 to be spent,\n /// amount1Desired The desired amount of token1 to be spent,\n /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,\n /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,\n /// deadline The time by which the transaction must be included to effect the change\n /// @return liquidity The new liquidity amount as a result of the increase\n /// @return amount0 The amount of token0 to acheive resulting liquidity\n /// @return amount1 The amount of token1 to acheive resulting liquidity\n function increaseLiquidity(IncreaseLiquidityParams calldata params)\n external\n payable\n returns (\n uint128 liquidity,\n uint256 amount0,\n uint256 amount1\n );\n\n struct DecreaseLiquidityParams {\n uint256 tokenId;\n uint128 liquidity;\n uint256 amount0Min;\n uint256 amount1Min;\n uint256 deadline;\n }\n\n /// @notice Decreases the amount of liquidity in a position and accounts it to the position\n /// @param params tokenId The ID of the token for which liquidity is being decreased,\n /// amount The amount by which liquidity will be decreased,\n /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,\n /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,\n /// deadline The time by which the transaction must be included to effect the change\n /// @return amount0 The amount of token0 accounted to the position's tokens owed\n /// @return amount1 The amount of token1 accounted to the position's tokens owed\n function decreaseLiquidity(DecreaseLiquidityParams calldata params)\n external\n payable\n returns (uint256 amount0, uint256 amount1);\n\n struct CollectParams {\n uint256 tokenId;\n address recipient;\n uint128 amount0Max;\n uint128 amount1Max;\n }\n\n /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient\n /// @param params tokenId The ID of the NFT for which tokens are being collected,\n /// recipient The account that should receive the tokens,\n /// amount0Max The maximum amount of token0 to collect,\n /// amount1Max The maximum amount of token1 to collect\n /// @return amount0 The amount of fees collected in token0\n /// @return amount1 The amount of fees collected in token1\n function collect(CollectParams calldata params)\n external\n payable\n returns (uint256 amount0, uint256 amount1);\n\n /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens\n /// must be collected first.\n /// @param tokenId The ID of the token that is being burned\n function burn(uint256 tokenId) external payable;\n}\n" }, "contracts/protocol/libraries/helpers/Helpers.sol": { "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.10;\n\nimport {IERC20} from \"../../../dependencies/openzeppelin/contracts/IERC20.sol\";\nimport {DataTypes} from \"../types/DataTypes.sol\";\n\n/**\n * @title Helpers library\n *\n */\nlibrary Helpers {\n /**\n * @notice Fetches the user current stable and variable debt balances\n * @param user The user address\n * @param debtTokenAddress The debt token address\n * @return The variable debt balance\n **/\n function getUserCurrentDebt(address user, address debtTokenAddress)\n internal\n view\n returns (uint256)\n {\n return (IERC20(debtTokenAddress).balanceOf(user));\n }\n}\n" }, "contracts/dependencies/uniswap/IPoolInitializer.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Creates and initializes V3 Pools\n/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that\n/// require the pool to exist.\ninterface IPoolInitializer {\n /// @notice Creates a new pool if it does not exist, then initializes if not initialized\n /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool\n /// @param token0 The contract address of token0 of the pool\n /// @param token1 The contract address of token1 of the pool\n /// @param fee The fee amount of the v3 pool for the specified token pair\n /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value\n /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary\n function createAndInitializePoolIfNecessary(\n address token0,\n address token1,\n uint24 fee,\n uint160 sqrtPriceX96\n ) external payable returns (address pool);\n}\n" }, "contracts/dependencies/uniswap/IERC721Permit.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\nimport \"../openzeppelin/contracts/IERC721.sol\";\n\n/// @title ERC721 with permit\n/// @notice Extension to ERC721 that includes a permit function for signature based approvals\ninterface IERC721Permit is IERC721 {\n /// @notice The permit typehash used in the permit signature\n /// @return The typehash for the permit\n function PERMIT_TYPEHASH() external pure returns (bytes32);\n\n /// @notice The domain separator used in the permit signature\n /// @return The domain seperator used in encoding of permit signature\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n\n /// @notice Approve of a specific token ID for spending by spender via signature\n /// @param spender The account that is being approved\n /// @param tokenId The ID of the token that is being approved for spending\n /// @param deadline The deadline timestamp by which the call must be mined for the approve to work\n /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`\n /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`\n /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`\n function permit(\n address spender,\n uint256 tokenId,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable;\n}\n" }, "contracts/dependencies/uniswap/IPeripheryPayments.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\n/// @title Periphery Payments\n/// @notice Functions to ease deposits and withdrawals of ETH\ninterface IPeripheryPayments {\n /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.\n /// @param amountMinimum The minimum amount of WETH9 to unwrap\n /// @param recipient The address receiving ETH\n function unwrapWETH9(uint256 amountMinimum, address recipient)\n external\n payable;\n\n /// @notice Refunds any ETH balance held by this contract to the `msg.sender`\n /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps\n /// that use ether for the input amount\n function refundETH() external payable;\n\n /// @notice Transfers the full amount of a token held by this contract to recipient\n /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users\n /// @param token The contract address of the token which will be transferred to `recipient`\n /// @param amountMinimum The minimum amount of token required for a transfer\n /// @param recipient The destination address of the token\n function sweepToken(\n address token,\n uint256 amountMinimum,\n address recipient\n ) external payable;\n}\n" }, "contracts/dependencies/uniswap/IPeripheryImmutableState.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Immutable state\n/// @notice Functions that return immutable state of the router\ninterface IPeripheryImmutableState {\n /// @return Returns the address of the Uniswap V3 factory\n function factory() external view returns (address);\n\n /// @return Returns the address of WETH9\n function WETH9() external view returns (address);\n}\n" }, "contracts/dependencies/uniswap/PoolAddress.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee\nlibrary PoolAddress {\n bytes32 internal constant POOL_INIT_CODE_HASH =\n 0xa598dd2fba360510c5a8f02f44423a4468e902df5857dbce3ca162a43a3a31ff;\n\n /// @notice The identifying key of the pool\n struct PoolKey {\n address token0;\n address token1;\n uint24 fee;\n }\n\n /// @notice Returns PoolKey: the ordered tokens with the matched fee levels\n /// @param tokenA The first token of a pool, unsorted\n /// @param tokenB The second token of a pool, unsorted\n /// @param fee The fee level of the pool\n /// @return Poolkey The pool details with ordered token0 and token1 assignments\n function getPoolKey(\n address tokenA,\n address tokenB,\n uint24 fee\n ) internal pure returns (PoolKey memory) {\n if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);\n return PoolKey({token0: tokenA, token1: tokenB, fee: fee});\n }\n\n /// @notice Deterministically computes the pool address given the factory and PoolKey\n /// @param factory The Uniswap V3 factory contract address\n /// @param key The PoolKey\n /// @return pool The contract address of the V3 pool\n function computeAddress(address factory, PoolKey memory key)\n internal\n pure\n returns (address pool)\n {\n require(key.token0 < key.token1);\n pool = address(\n uint160(\n uint256(\n keccak256(\n abi.encodePacked(\n hex\"ff\",\n factory,\n keccak256(\n abi.encode(key.token0, key.token1, key.fee)\n ),\n POOL_INIT_CODE_HASH\n )\n )\n )\n )\n );\n }\n}\n" }, "contracts/dependencies/openzeppelin/contracts/Math.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`.\n // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.\n // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.\n // Using an algorithm similar to the msb computation, we are able to compute `result = 2**(k/2)` which is a\n // good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1;\n uint256 x = a;\n if (x >> 128 > 0) {\n x >>= 128;\n result <<= 64;\n }\n if (x >> 64 > 0) {\n x >>= 64;\n result <<= 32;\n }\n if (x >> 32 > 0) {\n x >>= 32;\n result <<= 16;\n }\n if (x >> 16 > 0) {\n x >>= 16;\n result <<= 8;\n }\n if (x >> 8 > 0) {\n x >>= 8;\n result <<= 4;\n }\n if (x >> 4 > 0) {\n x >>= 4;\n result <<= 2;\n }\n if (x >> 2 > 0) {\n result <<= 1;\n }\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n uint256 result = sqrt(a);\n if (rounding == Rounding.Up && result * result < a) {\n result += 1;\n }\n return result;\n }\n}\n" }, "contracts/interfaces/INTokenUniswapV3.sol": { "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity 0.8.10;\n\ninterface INTokenUniswapV3 {\n /**\n * @notice Decreases liquidity for underlying Uniswap V3 NFT LP and validates\n * that the user respects liquidation checks.\n * @param user The user address decreasing liquidity for\n * @param tokenId The id of the erc721 token\n * @param liquidityDecrease The amount of liquidity to remove of LP\n * @param amount0Min The minimum amount to remove of token0\n * @param amount1Min The minimum amount to remove of token1\n * @param receiveEthAsWeth If convert weth to ETH\n */\n function decreaseUniswapV3Liquidity(\n address user,\n uint256 tokenId,\n uint128 liquidityDecrease,\n uint256 amount0Min,\n uint256 amount1Min,\n bool receiveEthAsWeth\n ) external;\n}\n" }, "contracts/dependencies/math/PRBMath.sol": { "content": "// SPDX-License-Identifier: Unlicense\npragma solidity >=0.8.4;\n\n/// @notice Emitted when the result overflows uint256.\nerror PRBMath__MulDivFixedPointOverflow(uint256 prod1);\n\n/// @notice Emitted when the result overflows uint256.\nerror PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator);\n\n/// @notice Emitted when one of the inputs is type(int256).min.\nerror PRBMath__MulDivSignedInputTooSmall();\n\n/// @notice Emitted when the intermediary absolute result overflows int256.\nerror PRBMath__MulDivSignedOverflow(uint256 rAbs);\n\n/// @notice Emitted when the input is MIN_SD59x18.\nerror PRBMathSD59x18__AbsInputTooSmall();\n\n/// @notice Emitted when ceiling a number overflows SD59x18.\nerror PRBMathSD59x18__CeilOverflow(int256 x);\n\n/// @notice Emitted when one of the inputs is MIN_SD59x18.\nerror PRBMathSD59x18__DivInputTooSmall();\n\n/// @notice Emitted when one of the intermediary unsigned results overflows SD59x18.\nerror PRBMathSD59x18__DivOverflow(uint256 rAbs);\n\n/// @notice Emitted when the input is greater than 133.084258667509499441.\nerror PRBMathSD59x18__ExpInputTooBig(int256 x);\n\n/// @notice Emitted when the input is greater than 192.\nerror PRBMathSD59x18__Exp2InputTooBig(int256 x);\n\n/// @notice Emitted when flooring a number underflows SD59x18.\nerror PRBMathSD59x18__FloorUnderflow(int256 x);\n\n/// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18.\nerror PRBMathSD59x18__FromIntOverflow(int256 x);\n\n/// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18.\nerror PRBMathSD59x18__FromIntUnderflow(int256 x);\n\n/// @notice Emitted when the product of the inputs is negative.\nerror PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y);\n\n/// @notice Emitted when multiplying the inputs overflows SD59x18.\nerror PRBMathSD59x18__GmOverflow(int256 x, int256 y);\n\n/// @notice Emitted when the input is less than or equal to zero.\nerror PRBMathSD59x18__LogInputTooSmall(int256 x);\n\n/// @notice Emitted when one of the inputs is MIN_SD59x18.\nerror PRBMathSD59x18__MulInputTooSmall();\n\n/// @notice Emitted when the intermediary absolute result overflows SD59x18.\nerror PRBMathSD59x18__MulOverflow(uint256 rAbs);\n\n/// @notice Emitted when the intermediary absolute result overflows SD59x18.\nerror PRBMathSD59x18__PowuOverflow(uint256 rAbs);\n\n/// @notice Emitted when the input is negative.\nerror PRBMathSD59x18__SqrtNegativeInput(int256 x);\n\n/// @notice Emitted when the calculating the square root overflows SD59x18.\nerror PRBMathSD59x18__SqrtOverflow(int256 x);\n\n/// @notice Emitted when addition overflows UD60x18.\nerror PRBMathUD60x18__AddOverflow(uint256 x, uint256 y);\n\n/// @notice Emitted when ceiling a number overflows UD60x18.\nerror PRBMathUD60x18__CeilOverflow(uint256 x);\n\n/// @notice Emitted when the input is greater than 133.084258667509499441.\nerror PRBMathUD60x18__ExpInputTooBig(uint256 x);\n\n/// @notice Emitted when the input is greater than 192.\nerror PRBMathUD60x18__Exp2InputTooBig(uint256 x);\n\n/// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18.\nerror PRBMathUD60x18__FromUintOverflow(uint256 x);\n\n/// @notice Emitted when multiplying the inputs overflows UD60x18.\nerror PRBMathUD60x18__GmOverflow(uint256 x, uint256 y);\n\n/// @notice Emitted when the input is less than 1.\nerror PRBMathUD60x18__LogInputTooSmall(uint256 x);\n\n/// @notice Emitted when the calculating the square root overflows UD60x18.\nerror PRBMathUD60x18__SqrtOverflow(uint256 x);\n\n/// @notice Emitted when subtraction underflows UD60x18.\nerror PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y);\n\n/// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library\n/// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point\n/// representation. When it does not, it is explicitly mentioned in the NatSpec documentation.\nlibrary PRBMath {\n /// STRUCTS ///\n\n struct SD59x18 {\n int256 value;\n }\n\n struct UD60x18 {\n uint256 value;\n }\n\n /// STORAGE ///\n\n /// @dev How many trailing decimals can be represented.\n uint256 internal constant SCALE = 1e18;\n\n /// @dev Largest power of two divisor of SCALE.\n uint256 internal constant SCALE_LPOTD = 262144;\n\n /// @dev SCALE inverted mod 2^256.\n uint256 internal constant SCALE_INVERSE =\n 78156646155174841979727994598816262306175212592076161876661_508869554232690281;\n\n /// FUNCTIONS ///\n\n /// @notice Calculates the binary exponent of x using the binary fraction method.\n /// @dev Has to use 192.64-bit fixed-point numbers.\n /// See https://ethereum.stackexchange.com/a/96594/24693.\n /// @param x The exponent as an unsigned 192.64-bit fixed-point number.\n /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n function exp2(uint256 x) internal pure returns (uint256 result) {\n unchecked {\n // Start from 0.5 in the 192.64-bit fixed-point format.\n result = 0x800000000000000000000000000000000000000000000000;\n\n // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows\n // because the initial result is 2^191 and all magic factors are less than 2^65.\n if (x & 0x8000000000000000 > 0) {\n result = (result * 0x16A09E667F3BCC909) >> 64;\n }\n if (x & 0x4000000000000000 > 0) {\n result = (result * 0x1306FE0A31B7152DF) >> 64;\n }\n if (x & 0x2000000000000000 > 0) {\n result = (result * 0x1172B83C7D517ADCE) >> 64;\n }\n if (x & 0x1000000000000000 > 0) {\n result = (result * 0x10B5586CF9890F62A) >> 64;\n }\n if (x & 0x800000000000000 > 0) {\n result = (result * 0x1059B0D31585743AE) >> 64;\n }\n if (x & 0x400000000000000 > 0) {\n result = (result * 0x102C9A3E778060EE7) >> 64;\n }\n if (x & 0x200000000000000 > 0) {\n result = (result * 0x10163DA9FB33356D8) >> 64;\n }\n if (x & 0x100000000000000 > 0) {\n result = (result * 0x100B1AFA5ABCBED61) >> 64;\n }\n if (x & 0x80000000000000 > 0) {\n result = (result * 0x10058C86DA1C09EA2) >> 64;\n }\n if (x & 0x40000000000000 > 0) {\n result = (result * 0x1002C605E2E8CEC50) >> 64;\n }\n if (x & 0x20000000000000 > 0) {\n result = (result * 0x100162F3904051FA1) >> 64;\n }\n if (x & 0x10000000000000 > 0) {\n result = (result * 0x1000B175EFFDC76BA) >> 64;\n }\n if (x & 0x8000000000000 > 0) {\n result = (result * 0x100058BA01FB9F96D) >> 64;\n }\n if (x & 0x4000000000000 > 0) {\n result = (result * 0x10002C5CC37DA9492) >> 64;\n }\n if (x & 0x2000000000000 > 0) {\n result = (result * 0x1000162E525EE0547) >> 64;\n }\n if (x & 0x1000000000000 > 0) {\n result = (result * 0x10000B17255775C04) >> 64;\n }\n if (x & 0x800000000000 > 0) {\n result = (result * 0x1000058B91B5BC9AE) >> 64;\n }\n if (x & 0x400000000000 > 0) {\n result = (result * 0x100002C5C89D5EC6D) >> 64;\n }\n if (x & 0x200000000000 > 0) {\n result = (result * 0x10000162E43F4F831) >> 64;\n }\n if (x & 0x100000000000 > 0) {\n result = (result * 0x100000B1721BCFC9A) >> 64;\n }\n if (x & 0x80000000000 > 0) {\n result = (result * 0x10000058B90CF1E6E) >> 64;\n }\n if (x & 0x40000000000 > 0) {\n result = (result * 0x1000002C5C863B73F) >> 64;\n }\n if (x & 0x20000000000 > 0) {\n result = (result * 0x100000162E430E5A2) >> 64;\n }\n if (x & 0x10000000000 > 0) {\n result = (result * 0x1000000B172183551) >> 64;\n }\n if (x & 0x8000000000 > 0) {\n result = (result * 0x100000058B90C0B49) >> 64;\n }\n if (x & 0x4000000000 > 0) {\n result = (result * 0x10000002C5C8601CC) >> 64;\n }\n if (x & 0x2000000000 > 0) {\n result = (result * 0x1000000162E42FFF0) >> 64;\n }\n if (x & 0x1000000000 > 0) {\n result = (result * 0x10000000B17217FBB) >> 64;\n }\n if (x & 0x800000000 > 0) {\n result = (result * 0x1000000058B90BFCE) >> 64;\n }\n if (x & 0x400000000 > 0) {\n result = (result * 0x100000002C5C85FE3) >> 64;\n }\n if (x & 0x200000000 > 0) {\n result = (result * 0x10000000162E42FF1) >> 64;\n }\n if (x & 0x100000000 > 0) {\n result = (result * 0x100000000B17217F8) >> 64;\n }\n if (x & 0x80000000 > 0) {\n result = (result * 0x10000000058B90BFC) >> 64;\n }\n if (x & 0x40000000 > 0) {\n result = (result * 0x1000000002C5C85FE) >> 64;\n }\n if (x & 0x20000000 > 0) {\n result = (result * 0x100000000162E42FF) >> 64;\n }\n if (x & 0x10000000 > 0) {\n result = (result * 0x1000000000B17217F) >> 64;\n }\n if (x & 0x8000000 > 0) {\n result = (result * 0x100000000058B90C0) >> 64;\n }\n if (x & 0x4000000 > 0) {\n result = (result * 0x10000000002C5C860) >> 64;\n }\n if (x & 0x2000000 > 0) {\n result = (result * 0x1000000000162E430) >> 64;\n }\n if (x & 0x1000000 > 0) {\n result = (result * 0x10000000000B17218) >> 64;\n }\n if (x & 0x800000 > 0) {\n result = (result * 0x1000000000058B90C) >> 64;\n }\n if (x & 0x400000 > 0) {\n result = (result * 0x100000000002C5C86) >> 64;\n }\n if (x & 0x200000 > 0) {\n result = (result * 0x10000000000162E43) >> 64;\n }\n if (x & 0x100000 > 0) {\n result = (result * 0x100000000000B1721) >> 64;\n }\n if (x & 0x80000 > 0) {\n result = (result * 0x10000000000058B91) >> 64;\n }\n if (x & 0x40000 > 0) {\n result = (result * 0x1000000000002C5C8) >> 64;\n }\n if (x & 0x20000 > 0) {\n result = (result * 0x100000000000162E4) >> 64;\n }\n if (x & 0x10000 > 0) {\n result = (result * 0x1000000000000B172) >> 64;\n }\n if (x & 0x8000 > 0) {\n result = (result * 0x100000000000058B9) >> 64;\n }\n if (x & 0x4000 > 0) {\n result = (result * 0x10000000000002C5D) >> 64;\n }\n if (x & 0x2000 > 0) {\n result = (result * 0x1000000000000162E) >> 64;\n }\n if (x & 0x1000 > 0) {\n result = (result * 0x10000000000000B17) >> 64;\n }\n if (x & 0x800 > 0) {\n result = (result * 0x1000000000000058C) >> 64;\n }\n if (x & 0x400 > 0) {\n result = (result * 0x100000000000002C6) >> 64;\n }\n if (x & 0x200 > 0) {\n result = (result * 0x10000000000000163) >> 64;\n }\n if (x & 0x100 > 0) {\n result = (result * 0x100000000000000B1) >> 64;\n }\n if (x & 0x80 > 0) {\n result = (result * 0x10000000000000059) >> 64;\n }\n if (x & 0x40 > 0) {\n result = (result * 0x1000000000000002C) >> 64;\n }\n if (x & 0x20 > 0) {\n result = (result * 0x10000000000000016) >> 64;\n }\n if (x & 0x10 > 0) {\n result = (result * 0x1000000000000000B) >> 64;\n }\n if (x & 0x8 > 0) {\n result = (result * 0x10000000000000006) >> 64;\n }\n if (x & 0x4 > 0) {\n result = (result * 0x10000000000000003) >> 64;\n }\n if (x & 0x2 > 0) {\n result = (result * 0x10000000000000001) >> 64;\n }\n if (x & 0x1 > 0) {\n result = (result * 0x10000000000000001) >> 64;\n }\n\n // We're doing two things at the same time:\n //\n // 1. Multiply the result by 2^n + 1, where \"2^n\" is the integer part and the one is added to account for\n // the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191\n // rather than 192.\n // 2. Convert the result to the unsigned 60.18-decimal fixed-point format.\n //\n // This works because 2^(191-ip) = 2^ip / 2^191, where \"ip\" is the integer part \"2^n\".\n result *= SCALE;\n result >>= (191 - (x >> 64));\n }\n }\n\n /// @notice Finds the zero-based index of the first one in the binary representation of x.\n /// @dev See the note on msb in the \"Find First Set\" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set\n /// @param x The uint256 number for which to find the index of the most significant bit.\n /// @return msb The index of the most significant bit as an uint256.\n function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) {\n if (x >= 2**128) {\n x >>= 128;\n msb += 128;\n }\n if (x >= 2**64) {\n x >>= 64;\n msb += 64;\n }\n if (x >= 2**32) {\n x >>= 32;\n msb += 32;\n }\n if (x >= 2**16) {\n x >>= 16;\n msb += 16;\n }\n if (x >= 2**8) {\n x >>= 8;\n msb += 8;\n }\n if (x >= 2**4) {\n x >>= 4;\n msb += 4;\n }\n if (x >= 2**2) {\n x >>= 2;\n msb += 2;\n }\n if (x >= 2**1) {\n // No need to shift x any more.\n msb += 1;\n }\n }\n\n /// @notice Calculates floor(x*y÷denominator) with full precision.\n ///\n /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.\n ///\n /// Requirements:\n /// - The denominator cannot be zero.\n /// - The result must fit within uint256.\n ///\n /// Caveats:\n /// - This function does not work with fixed-point numbers.\n ///\n /// @param x The multiplicand as an uint256.\n /// @param y The multiplier as an uint256.\n /// @param denominator The divisor as an uint256.\n /// @return result The result as an uint256.\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n unchecked {\n result = prod0 / denominator;\n }\n return result;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n if (prod1 >= denominator) {\n revert PRBMath__MulDivOverflow(prod1, denominator);\n }\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n unchecked {\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 lpotdod = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by lpotdod.\n denominator := div(denominator, lpotdod)\n\n // Divide [prod1 prod0] by lpotdod.\n prod0 := div(prod0, lpotdod)\n\n // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one.\n lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * lpotdod;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /// @notice Calculates floor(x*y÷1e18) with full precision.\n ///\n /// @dev Variant of \"mulDiv\" with constant folding, i.e. in which the denominator is always 1e18. Before returning the\n /// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of\n /// being rounded to 1e-18. See \"Listing 6\" and text above it at https://accu.org/index.php/journals/1717.\n ///\n /// Requirements:\n /// - The result must fit within uint256.\n ///\n /// Caveats:\n /// - The body is purposely left uncommented; see the NatSpec comments in \"PRBMath.mulDiv\" to understand how this works.\n /// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations:\n /// 1. x * y = type(uint256).max * SCALE\n /// 2. (x * y) % SCALE >= SCALE / 2\n ///\n /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.\n /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.\n /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) {\n uint256 prod0;\n uint256 prod1;\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n if (prod1 >= SCALE) {\n revert PRBMath__MulDivFixedPointOverflow(prod1);\n }\n\n uint256 remainder;\n uint256 roundUpUnit;\n assembly {\n remainder := mulmod(x, y, SCALE)\n roundUpUnit := gt(remainder, 499999999999999999)\n }\n\n if (prod1 == 0) {\n unchecked {\n result = (prod0 / SCALE) + roundUpUnit;\n return result;\n }\n }\n\n assembly {\n result := add(\n mul(\n or(\n div(sub(prod0, remainder), SCALE_LPOTD),\n mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1))\n ),\n SCALE_INVERSE\n ),\n roundUpUnit\n )\n }\n }\n\n /// @notice Calculates floor(x*y÷denominator) with full precision.\n ///\n /// @dev An extension of \"mulDiv\" for signed numbers. Works by computing the signs and the absolute values separately.\n ///\n /// Requirements:\n /// - None of the inputs can be type(int256).min.\n /// - The result must fit within int256.\n ///\n /// @param x The multiplicand as an int256.\n /// @param y The multiplier as an int256.\n /// @param denominator The divisor as an int256.\n /// @return result The result as an int256.\n function mulDivSigned(\n int256 x,\n int256 y,\n int256 denominator\n ) internal pure returns (int256 result) {\n if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {\n revert PRBMath__MulDivSignedInputTooSmall();\n }\n\n // Get hold of the absolute values of x, y and the denominator.\n uint256 ax;\n uint256 ay;\n uint256 ad;\n unchecked {\n ax = x < 0 ? uint256(-x) : uint256(x);\n ay = y < 0 ? uint256(-y) : uint256(y);\n ad = denominator < 0 ? uint256(-denominator) : uint256(denominator);\n }\n\n // Compute the absolute value of (x*y)÷denominator. The result must fit within int256.\n uint256 rAbs = mulDiv(ax, ay, ad);\n if (rAbs > uint256(type(int256).max)) {\n revert PRBMath__MulDivSignedOverflow(rAbs);\n }\n\n // Get the signs of x, y and the denominator.\n uint256 sx;\n uint256 sy;\n uint256 sd;\n assembly {\n sx := sgt(x, sub(0, 1))\n sy := sgt(y, sub(0, 1))\n sd := sgt(denominator, sub(0, 1))\n }\n\n // XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs.\n // If yes, the result should be negative.\n result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);\n }\n\n /// @notice Calculates the square root of x, rounding down.\n /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n ///\n /// Caveats:\n /// - This function does not work with fixed-point numbers.\n ///\n /// @param x The uint256 number for which to calculate the square root.\n /// @return result The result as an uint256.\n function sqrt(uint256 x) internal pure returns (uint256 result) {\n if (x == 0) {\n return 0;\n }\n\n // Set the initial guess to the least power of two that is greater than or equal to sqrt(x).\n uint256 xAux = uint256(x);\n result = 1;\n if (xAux >= 0x100000000000000000000000000000000) {\n xAux >>= 128;\n result <<= 64;\n }\n if (xAux >= 0x10000000000000000) {\n xAux >>= 64;\n result <<= 32;\n }\n if (xAux >= 0x100000000) {\n xAux >>= 32;\n result <<= 16;\n }\n if (xAux >= 0x10000) {\n xAux >>= 16;\n result <<= 8;\n }\n if (xAux >= 0x100) {\n xAux >>= 8;\n result <<= 4;\n }\n if (xAux >= 0x10) {\n xAux >>= 4;\n result <<= 2;\n }\n if (xAux >= 0x4) {\n result <<= 1;\n }\n\n // The operations can never overflow because the result is max 2^127 when it enters this block.\n unchecked {\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1;\n result = (result + x / result) >> 1; // Seven iterations should be enough\n uint256 roundedDownResult = x / result;\n return result >= roundedDownResult ? roundedDownResult : result;\n }\n }\n}\n" }, "contracts/dependencies/math/PRBMathUD60x18.sol": { "content": "// SPDX-License-Identifier: Unlicense\npragma solidity >=0.8.4;\n\nimport \"./PRBMath.sol\";\n\n/// @title PRBMathUD60x18\n/// @author Paul Razvan Berg\n/// @notice Smart contract library for advanced fixed-point math that works with uint256 numbers considered to have 18\n/// trailing decimals. We call this number representation unsigned 60.18-decimal fixed-point, since there can be up to 60\n/// digits in the integer part and up to 18 decimals in the fractional part. The numbers are bound by the minimum and the\n/// maximum values permitted by the Solidity type uint256.\nlibrary PRBMathUD60x18 {\n /// @dev Half the SCALE number.\n uint256 internal constant HALF_SCALE = 5e17;\n\n /// @dev log2(e) as an unsigned 60.18-decimal fixed-point number.\n uint256 internal constant LOG2_E = 1_442695040888963407;\n\n /// @dev The maximum value an unsigned 60.18-decimal fixed-point number can have.\n uint256 internal constant MAX_UD60x18 =\n 115792089237316195423570985008687907853269984665640564039457_584007913129639935;\n\n /// @dev The maximum whole value an unsigned 60.18-decimal fixed-point number can have.\n uint256 internal constant MAX_WHOLE_UD60x18 =\n 115792089237316195423570985008687907853269984665640564039457_000000000000000000;\n\n /// @dev How many trailing decimals can be represented.\n uint256 internal constant SCALE = 1e18;\n\n /// @notice Calculates the arithmetic average of x and y, rounding down.\n /// @param x The first operand as an unsigned 60.18-decimal fixed-point number.\n /// @param y The second operand as an unsigned 60.18-decimal fixed-point number.\n /// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number.\n function avg(uint256 x, uint256 y) internal pure returns (uint256 result) {\n // The operations can never overflow.\n unchecked {\n // The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need\n // to do this because if both numbers are odd, the 0.5 remainder gets truncated twice.\n result = (x >> 1) + (y >> 1) + (x & y & 1);\n }\n }\n\n /// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x.\n ///\n /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n ///\n /// Requirements:\n /// - x must be less than or equal to MAX_WHOLE_UD60x18.\n ///\n /// @param x The unsigned 60.18-decimal fixed-point number to ceil.\n /// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number.\n function ceil(uint256 x) internal pure returns (uint256 result) {\n if (x > MAX_WHOLE_UD60x18) {\n revert PRBMathUD60x18__CeilOverflow(x);\n }\n assembly {\n // Equivalent to \"x % SCALE\" but faster.\n let remainder := mod(x, SCALE)\n\n // Equivalent to \"SCALE - remainder\" but faster.\n let delta := sub(SCALE, remainder)\n\n // Equivalent to \"x + delta * (remainder > 0 ? 1 : 0)\" but faster.\n result := add(x, mul(delta, gt(remainder, 0)))\n }\n }\n\n /// @notice Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number.\n ///\n /// @dev Uses mulDiv to enable overflow-safe multiplication and division.\n ///\n /// Requirements:\n /// - The denominator cannot be zero.\n ///\n /// @param x The numerator as an unsigned 60.18-decimal fixed-point number.\n /// @param y The denominator as an unsigned 60.18-decimal fixed-point number.\n /// @param result The quotient as an unsigned 60.18-decimal fixed-point number.\n function div(uint256 x, uint256 y) internal pure returns (uint256 result) {\n result = PRBMath.mulDiv(x, SCALE, y);\n }\n\n /// @notice Returns Euler's number as an unsigned 60.18-decimal fixed-point number.\n /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).\n function e() internal pure returns (uint256 result) {\n result = 2_718281828459045235;\n }\n\n /// @notice Calculates the natural exponent of x.\n ///\n /// @dev Based on the insight that e^x = 2^(x * log2(e)).\n ///\n /// Requirements:\n /// - All from \"log2\".\n /// - x must be less than 133.084258667509499441.\n ///\n /// @param x The exponent as an unsigned 60.18-decimal fixed-point number.\n /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n function exp(uint256 x) internal pure returns (uint256 result) {\n // Without this check, the value passed to \"exp2\" would be greater than 192.\n if (x >= 133_084258667509499441) {\n revert PRBMathUD60x18__ExpInputTooBig(x);\n }\n\n // Do the fixed-point multiplication inline to save gas.\n unchecked {\n uint256 doubleScaleProduct = x * LOG2_E;\n result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);\n }\n }\n\n /// @notice Calculates the binary exponent of x using the binary fraction method.\n ///\n /// @dev See https://ethereum.stackexchange.com/q/79903/24693.\n ///\n /// Requirements:\n /// - x must be 192 or less.\n /// - The result must fit within MAX_UD60x18.\n ///\n /// @param x The exponent as an unsigned 60.18-decimal fixed-point number.\n /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n function exp2(uint256 x) internal pure returns (uint256 result) {\n // 2^192 doesn't fit within the 192.64-bit format used internally in this function.\n if (x >= 192e18) {\n revert PRBMathUD60x18__Exp2InputTooBig(x);\n }\n\n unchecked {\n // Convert x to the 192.64-bit fixed-point format.\n uint256 x192x64 = (x << 64) / SCALE;\n\n // Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation.\n result = PRBMath.exp2(x192x64);\n }\n }\n\n /// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x.\n /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n /// @param x The unsigned 60.18-decimal fixed-point number to floor.\n /// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number.\n function floor(uint256 x) internal pure returns (uint256 result) {\n assembly {\n // Equivalent to \"x % SCALE\" but faster.\n let remainder := mod(x, SCALE)\n\n // Equivalent to \"x - remainder * (remainder > 0 ? 1 : 0)\" but faster.\n result := sub(x, mul(remainder, gt(remainder, 0)))\n }\n }\n\n /// @notice Yields the excess beyond the floor of x.\n /// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part.\n /// @param x The unsigned 60.18-decimal fixed-point number to get the fractional part of.\n /// @param result The fractional part of x as an unsigned 60.18-decimal fixed-point number.\n function frac(uint256 x) internal pure returns (uint256 result) {\n assembly {\n result := mod(x, SCALE)\n }\n }\n\n /// @notice Converts a number from basic integer form to unsigned 60.18-decimal fixed-point representation.\n ///\n /// @dev Requirements:\n /// - x must be less than or equal to MAX_UD60x18 divided by SCALE.\n ///\n /// @param x The basic integer to convert.\n /// @param result The same number in unsigned 60.18-decimal fixed-point representation.\n function fromUint(uint256 x) internal pure returns (uint256 result) {\n unchecked {\n if (x > MAX_UD60x18 / SCALE) {\n revert PRBMathUD60x18__FromUintOverflow(x);\n }\n result = x * SCALE;\n }\n }\n\n /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.\n ///\n /// @dev Requirements:\n /// - x * y must fit within MAX_UD60x18, lest it overflows.\n ///\n /// @param x The first operand as an unsigned 60.18-decimal fixed-point number.\n /// @param y The second operand as an unsigned 60.18-decimal fixed-point number.\n /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n function gm(uint256 x, uint256 y) internal pure returns (uint256 result) {\n if (x == 0) {\n return 0;\n }\n\n unchecked {\n // Checking for overflow this way is faster than letting Solidity do it.\n uint256 xy = x * y;\n if (xy / x != y) {\n revert PRBMathUD60x18__GmOverflow(x, y);\n }\n\n // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE\n // during multiplication. See the comments within the \"sqrt\" function.\n result = PRBMath.sqrt(xy);\n }\n }\n\n /// @notice Calculates 1 / x, rounding toward zero.\n ///\n /// @dev Requirements:\n /// - x cannot be zero.\n ///\n /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the inverse.\n /// @return result The inverse as an unsigned 60.18-decimal fixed-point number.\n function inv(uint256 x) internal pure returns (uint256 result) {\n unchecked {\n // 1e36 is SCALE * SCALE.\n result = 1e36 / x;\n }\n }\n\n /// @notice Calculates the natural logarithm of x.\n ///\n /// @dev Based on the insight that ln(x) = log2(x) / log2(e).\n ///\n /// Requirements:\n /// - All from \"log2\".\n ///\n /// Caveats:\n /// - All from \"log2\".\n /// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision.\n ///\n /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm.\n /// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number.\n function ln(uint256 x) internal pure returns (uint256 result) {\n // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)\n // can return is 196205294292027477728.\n unchecked {\n result = (log2(x) * SCALE) / LOG2_E;\n }\n }\n\n /// @notice Calculates the common logarithm of x.\n ///\n /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common\n /// logarithm based on the insight that log10(x) = log2(x) / log2(10).\n ///\n /// Requirements:\n /// - All from \"log2\".\n ///\n /// Caveats:\n /// - All from \"log2\".\n ///\n /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the common logarithm.\n /// @return result The common logarithm as an unsigned 60.18-decimal fixed-point number.\n function log10(uint256 x) internal pure returns (uint256 result) {\n if (x < SCALE) {\n revert PRBMathUD60x18__LogInputTooSmall(x);\n }\n\n // Note that the \"mul\" in this block is the assembly multiplication operation, not the \"mul\" function defined\n // in this contract.\n // prettier-ignore\n assembly {\n switch x\n case 1 { result := mul(SCALE, sub(0, 18)) }\n case 10 { result := mul(SCALE, sub(1, 18)) }\n case 100 { result := mul(SCALE, sub(2, 18)) }\n case 1000 { result := mul(SCALE, sub(3, 18)) }\n case 10000 { result := mul(SCALE, sub(4, 18)) }\n case 100000 { result := mul(SCALE, sub(5, 18)) }\n case 1000000 { result := mul(SCALE, sub(6, 18)) }\n case 10000000 { result := mul(SCALE, sub(7, 18)) }\n case 100000000 { result := mul(SCALE, sub(8, 18)) }\n case 1000000000 { result := mul(SCALE, sub(9, 18)) }\n case 10000000000 { result := mul(SCALE, sub(10, 18)) }\n case 100000000000 { result := mul(SCALE, sub(11, 18)) }\n case 1000000000000 { result := mul(SCALE, sub(12, 18)) }\n case 10000000000000 { result := mul(SCALE, sub(13, 18)) }\n case 100000000000000 { result := mul(SCALE, sub(14, 18)) }\n case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }\n case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }\n case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }\n case 1000000000000000000 { result := 0 }\n case 10000000000000000000 { result := SCALE }\n case 100000000000000000000 { result := mul(SCALE, 2) }\n case 1000000000000000000000 { result := mul(SCALE, 3) }\n case 10000000000000000000000 { result := mul(SCALE, 4) }\n case 100000000000000000000000 { result := mul(SCALE, 5) }\n case 1000000000000000000000000 { result := mul(SCALE, 6) }\n case 10000000000000000000000000 { result := mul(SCALE, 7) }\n case 100000000000000000000000000 { result := mul(SCALE, 8) }\n case 1000000000000000000000000000 { result := mul(SCALE, 9) }\n case 10000000000000000000000000000 { result := mul(SCALE, 10) }\n case 100000000000000000000000000000 { result := mul(SCALE, 11) }\n case 1000000000000000000000000000000 { result := mul(SCALE, 12) }\n case 10000000000000000000000000000000 { result := mul(SCALE, 13) }\n case 100000000000000000000000000000000 { result := mul(SCALE, 14) }\n case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }\n case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }\n case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }\n case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }\n case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }\n case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }\n case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }\n case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }\n case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }\n case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }\n case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }\n case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }\n case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }\n case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }\n case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }\n case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }\n case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }\n case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }\n case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }\n case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }\n case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }\n case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) }\n case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) }\n case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) }\n case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) }\n case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) }\n case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) }\n case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) }\n case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) }\n case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) }\n case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) }\n case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) }\n case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) }\n case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) }\n case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) }\n case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) }\n case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) }\n case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) }\n case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) }\n case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) }\n case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) }\n case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) }\n case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) }\n case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) }\n case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 59) }\n default {\n result := MAX_UD60x18\n }\n }\n\n if (result == MAX_UD60x18) {\n // Do the fixed-point division inline to save gas. The denominator is log2(10).\n unchecked {\n result = (log2(x) * SCALE) / 3_321928094887362347;\n }\n }\n }\n\n /// @notice Calculates the binary logarithm of x.\n ///\n /// @dev Based on the iterative approximation algorithm.\n /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation\n ///\n /// Requirements:\n /// - x must be greater than or equal to SCALE, otherwise the result would be negative.\n ///\n /// Caveats:\n /// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.\n ///\n /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the binary logarithm.\n /// @return result The binary logarithm as an unsigned 60.18-decimal fixed-point number.\n function log2(uint256 x) internal pure returns (uint256 result) {\n if (x < SCALE) {\n revert PRBMathUD60x18__LogInputTooSmall(x);\n }\n unchecked {\n // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).\n uint256 n = PRBMath.mostSignificantBit(x / SCALE);\n\n // The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow\n // because n is maximum 255 and SCALE is 1e18.\n result = n * SCALE;\n\n // This is y = x * 2^(-n).\n uint256 y = x >> n;\n\n // If y = 1, the fractional part is zero.\n if (y == SCALE) {\n return result;\n }\n\n // Calculate the fractional part via the iterative approximation.\n // The \"delta >>= 1\" part is equivalent to \"delta /= 2\", but shifting bits is faster.\n for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) {\n y = (y * y) / SCALE;\n\n // Is y^2 > 2 and so in the range [2,4)?\n if (y >= 2 * SCALE) {\n // Add the 2^(-m) factor to the logarithm.\n result += delta;\n\n // Corresponds to z/2 on Wikipedia.\n y >>= 1;\n }\n }\n }\n }\n\n /// @notice Multiplies two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal\n /// fixed-point number.\n /// @dev See the documentation for the \"PRBMath.mulDivFixedPoint\" function.\n /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.\n /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.\n /// @return result The product as an unsigned 60.18-decimal fixed-point number.\n function mul(uint256 x, uint256 y) internal pure returns (uint256 result) {\n result = PRBMath.mulDivFixedPoint(x, y);\n }\n\n /// @notice Returns PI as an unsigned 60.18-decimal fixed-point number.\n function pi() internal pure returns (uint256 result) {\n result = 3_141592653589793238;\n }\n\n /// @notice Raises x to the power of y.\n ///\n /// @dev Based on the insight that x^y = 2^(log2(x) * y).\n ///\n /// Requirements:\n /// - All from \"exp2\", \"log2\" and \"mul\".\n ///\n /// Caveats:\n /// - All from \"exp2\", \"log2\" and \"mul\".\n /// - Assumes 0^0 is 1.\n ///\n /// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number.\n /// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number.\n /// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number.\n function pow(uint256 x, uint256 y) internal pure returns (uint256 result) {\n if (x == 0) {\n result = y == 0 ? SCALE : uint256(0);\n } else {\n result = exp2(mul(log2(x), y));\n }\n }\n\n /// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the\n /// famous algorithm \"exponentiation by squaring\".\n ///\n /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring\n ///\n /// Requirements:\n /// - The result must fit within MAX_UD60x18.\n ///\n /// Caveats:\n /// - All from \"mul\".\n /// - Assumes 0^0 is 1.\n ///\n /// @param x The base as an unsigned 60.18-decimal fixed-point number.\n /// @param y The exponent as an uint256.\n /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n function powu(uint256 x, uint256 y) internal pure returns (uint256 result) {\n // Calculate the first iteration of the loop in advance.\n result = y & 1 > 0 ? x : SCALE;\n\n // Equivalent to \"for(y /= 2; y > 0; y /= 2)\" but faster.\n for (y >>= 1; y > 0; y >>= 1) {\n x = PRBMath.mulDivFixedPoint(x, x);\n\n // Equivalent to \"y % 2 == 1\" but faster.\n if (y & 1 > 0) {\n result = PRBMath.mulDivFixedPoint(result, x);\n }\n }\n }\n\n /// @notice Returns 1 as an unsigned 60.18-decimal fixed-point number.\n function scale() internal pure returns (uint256 result) {\n result = SCALE;\n }\n\n /// @notice Calculates the square root of x, rounding down.\n /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n ///\n /// Requirements:\n /// - x must be less than MAX_UD60x18 / SCALE.\n ///\n /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root.\n /// @return result The result as an unsigned 60.18-decimal fixed-point .\n function sqrt(uint256 x) internal pure returns (uint256 result) {\n unchecked {\n if (x > MAX_UD60x18 / SCALE) {\n revert PRBMathUD60x18__SqrtOverflow(x);\n }\n // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned\n // 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).\n result = PRBMath.sqrt(x * SCALE);\n }\n }\n\n /// @notice Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process.\n /// @param x The unsigned 60.18-decimal fixed-point number to convert.\n /// @return result The same number in basic integer form.\n function toUint(uint256 x) internal pure returns (uint256 result) {\n unchecked {\n result = x / SCALE;\n }\n }\n}\n" }, "contracts/misc/interfaces/IFlashClaimReceiver.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.10;\n\n/**\n * @title IFlashClaimReceiver interface\n * @dev implement this interface to develop a flashclaim-compatible flashClaimReceiver contract\n **/\ninterface IFlashClaimReceiver {\n function executeOperation(\n address asset,\n uint256[] calldata tokenIds,\n bytes calldata params\n ) external returns (bool);\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 4000 }, "evmVersion": "london", "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": { "contracts/protocol/libraries/logic/AuctionLogic.sol": { "AuctionLogic": "0x860e44ae07a3549d769ceaa6a7ae37a96f5132cb" }, "contracts/protocol/libraries/logic/LiquidationLogic.sol": { "LiquidationLogic": "0xe6668ecb714d17382bf307fb023fc4b0e348f80b" }, "contracts/protocol/libraries/logic/SupplyLogic.sol": { "SupplyLogic": "0xa8caa91b746a03be130573b7b30ce3813b21905b" }, "contracts/protocol/libraries/logic/BorrowLogic.sol": { "BorrowLogic": "0x5a766c175f517cc27caf55802b230970a783eb9d" }, "contracts/protocol/libraries/logic/FlashClaimLogic.sol": { "FlashClaimLogic": "0xc63e0783b5331f8971b22ac13871d17d4a70c23f" } } } }