{ "language": "Solidity", "sources": { "contracts/adapters/OpenseaAdapter.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\nimport {IOpenseaExchage} from \"../interfaces/IOpenseaExchage.sol\";\n\nimport {BaseAdapter, IERC721Upgradeable} from \"./BaseAdapter.sol\";\n\ncontract OpenseaAdapter is BaseAdapter {\n string public constant NAME = \"Opensea Downpayment Adapter\";\n string public constant VERSION = \"1.0\";\n // keccak256(\"Sig(uint8 v,bytes32 r,bytes32 s)\")\n bytes32 internal constant _SIGNATURE_TYPEHASH = 0x7113392a96292fcdb631e265c62d67694adea92a7ecaaab03d2b75203232c507;\n // keccak256(\"Params(address nftAsset,uint256 nftTokenId,Order buy,Sig buySig,Order sell,Sig sellSig,bytes32 metadata,uint256 nonce)Order(address exchange,address maker,address taker,uint256 makerRelayerFee,uint256 takerRelayerFee,uint256 makerProtocolFee,uint256 takerProtocolFee,address feeRecipient,uint8 feeMethod,uint8 side,uint8 saleKind,address target,uint8 howToCall,bytes calldata,bytes replacementPattern,address staticTarget,bytes staticExtradata,address paymentToken,uint256 basePrice,uint256 extra,uint256 listingTime,uint256 expirationTime,uint256 salt)Sig(uint8 v,bytes32 r,bytes32 s)\")\n bytes32 private constant _PARAMS_TYPEHASH = 0x45a3a5167053dac828db3853d0bf488bf3f097cddee9ea72e6e57ef7c40c4e40;\n // keccak256(\"Order(address exchange,address maker,address taker,uint256 makerRelayerFee,uint256 takerRelayerFee,uint256 makerProtocolFee,uint256 takerProtocolFee,address feeRecipient,uint8 feeMethod,uint8 side,uint8 saleKind,address target,uint8 howToCall,bytes calldata,bytes replacementPattern,address staticTarget,bytes staticExtradata,address paymentToken,uint256 basePrice,uint256 extra,uint256 listingTime,uint256 expirationTime,uint256 salt)\")\n bytes32 private constant _ORDER_TYPEHASH = 0xe8278750458fc9dce622c9801945913be199be75b96fd73d1432029651d75b7f;\n\n IOpenseaExchage public openseaExchange;\n address private proxy;\n\n struct Params {\n // bend params\n address nftAsset;\n uint256 nftTokenId;\n // opensea params\n address[14] addrs;\n uint256[18] uints;\n uint8[8] feeMethodsSidesKindsHowToCalls;\n bytes calldataBuy;\n bytes calldataSell;\n bytes replacementPatternBuy;\n bytes replacementPatternSell;\n bytes staticExtradataBuy;\n bytes staticExtradataSell;\n uint8[2] vs;\n bytes32[5] rssMetadata;\n }\n\n struct Sig {\n uint8 v;\n bytes32 r;\n bytes32 s;\n }\n\n struct Order {\n address exchange;\n address maker;\n address taker;\n uint256 makerRelayerFee;\n uint256 takerRelayerFee;\n uint256 makerProtocolFee;\n uint256 takerProtocolFee;\n address feeRecipient;\n uint8 feeMethod;\n uint8 side;\n uint8 saleKind;\n address target;\n uint8 howToCall;\n bytes data;\n bytes replacementPattern;\n address staticTarget;\n bytes staticExtradata;\n address paymentToken;\n uint256 basePrice;\n uint256 extra;\n uint256 listingTime;\n uint256 expirationTime;\n uint256 salt;\n }\n\n function initialize(address _downpayment, address _openseaExchange) external initializer {\n __BaseAdapter_init(NAME, VERSION, _downpayment);\n openseaExchange = IOpenseaExchage(_openseaExchange);\n proxy = openseaExchange.tokenTransferProxy();\n }\n\n function initWETH() external reinitializer(2) {\n __BaseAdapter_init(NAME, VERSION, address(downpayment));\n }\n\n struct CheckOrderParamsLocalVars {\n address buyerpaymentToken;\n address sellerpaymentToken;\n uint256 buyPrice;\n uint256 sellPrice;\n }\n\n function _checkParams(\n address,\n uint256,\n uint256,\n bytes memory _params,\n uint256 _nonce\n ) internal view override returns (BaseParams memory) {\n CheckOrderParamsLocalVars memory vars;\n\n Params memory _orderParams = _decodeParams(_params);\n address _WETH = address(WETH);\n\n // Check order params\n require(address(this) == _orderParams.addrs[1], \"Adapter: buyer address error\");\n vars.buyerpaymentToken = _orderParams.addrs[6];\n vars.sellerpaymentToken = _orderParams.addrs[13];\n require(\n address(0) == vars.buyerpaymentToken || _WETH == vars.buyerpaymentToken,\n \"Adapter: buyer payment token should be ETH or WETH\"\n );\n require(\n address(0) == vars.sellerpaymentToken || _WETH == vars.buyerpaymentToken,\n \"Adapter: seller payment token should be ETH or WETH\"\n );\n require(\n _orderParams.feeMethodsSidesKindsHowToCalls[2] == _orderParams.feeMethodsSidesKindsHowToCalls[6] &&\n 0 == _orderParams.feeMethodsSidesKindsHowToCalls[2],\n \"Adapter: order must be fixed price sale kind\"\n );\n\n vars.buyPrice = _orderParams.uints[4];\n vars.sellPrice = _orderParams.uints[13];\n require(vars.buyPrice == vars.sellPrice, \"Adapter: order price must be same\");\n\n return\n BaseParams({\n nftAsset: _orderParams.nftAsset,\n nftTokenId: _orderParams.nftTokenId,\n currency: vars.buyerpaymentToken,\n salePrice: vars.sellPrice,\n paramsHash: _hashParams(_orderParams, _nonce)\n });\n }\n\n function _hashParams(Params memory _orderParams, uint256 _nonce) internal pure returns (bytes32) {\n Order memory buy;\n {\n buy.exchange = _orderParams.addrs[0];\n buy.maker = _orderParams.addrs[1];\n buy.taker = _orderParams.addrs[2];\n buy.makerRelayerFee = _orderParams.uints[0];\n buy.takerRelayerFee = _orderParams.uints[1];\n buy.makerProtocolFee = _orderParams.uints[2];\n buy.takerProtocolFee = _orderParams.uints[3];\n buy.feeRecipient = _orderParams.addrs[3];\n buy.feeMethod = _orderParams.feeMethodsSidesKindsHowToCalls[0];\n buy.side = _orderParams.feeMethodsSidesKindsHowToCalls[1];\n buy.saleKind = _orderParams.feeMethodsSidesKindsHowToCalls[2];\n buy.target = _orderParams.addrs[4];\n buy.howToCall = _orderParams.feeMethodsSidesKindsHowToCalls[3];\n buy.data = _orderParams.calldataBuy;\n buy.replacementPattern = _orderParams.replacementPatternBuy;\n buy.staticTarget = _orderParams.addrs[5];\n buy.staticExtradata = _orderParams.staticExtradataBuy;\n buy.paymentToken = _orderParams.addrs[6];\n buy.basePrice = _orderParams.uints[4];\n buy.extra = _orderParams.uints[5];\n buy.listingTime = _orderParams.uints[6];\n buy.expirationTime = _orderParams.uints[7];\n buy.salt = _orderParams.uints[8];\n }\n Order memory sell;\n {\n sell.exchange = _orderParams.addrs[7];\n sell.maker = _orderParams.addrs[8];\n sell.taker = _orderParams.addrs[9];\n sell.makerRelayerFee = _orderParams.uints[9];\n sell.takerRelayerFee = _orderParams.uints[10];\n sell.makerProtocolFee = _orderParams.uints[11];\n sell.takerProtocolFee = _orderParams.uints[12];\n sell.feeRecipient = _orderParams.addrs[10];\n sell.feeMethod = _orderParams.feeMethodsSidesKindsHowToCalls[4];\n sell.side = _orderParams.feeMethodsSidesKindsHowToCalls[5];\n sell.saleKind = _orderParams.feeMethodsSidesKindsHowToCalls[6];\n sell.target = _orderParams.addrs[11];\n sell.howToCall = _orderParams.feeMethodsSidesKindsHowToCalls[7];\n sell.data = _orderParams.calldataSell;\n sell.replacementPattern = _orderParams.replacementPatternSell;\n sell.staticTarget = _orderParams.addrs[12];\n sell.staticExtradata = _orderParams.staticExtradataSell;\n sell.paymentToken = _orderParams.addrs[13];\n sell.basePrice = _orderParams.uints[13];\n sell.extra = _orderParams.uints[14];\n sell.listingTime = _orderParams.uints[15];\n sell.expirationTime = _orderParams.uints[16];\n sell.salt = _orderParams.uints[17];\n }\n\n Sig memory buySig;\n {\n buySig.v = _orderParams.vs[0];\n buySig.r = _orderParams.rssMetadata[0];\n buySig.s = _orderParams.rssMetadata[1];\n }\n\n Sig memory sellSig;\n {\n sellSig.v = _orderParams.vs[1];\n sellSig.r = _orderParams.rssMetadata[2];\n sellSig.s = _orderParams.rssMetadata[3];\n }\n\n return\n keccak256(\n abi.encode(\n _PARAMS_TYPEHASH,\n _orderParams.nftAsset,\n _orderParams.nftTokenId,\n _hashOrder(buy),\n _hashSig(buySig),\n _hashOrder(sell),\n _hashSig(sellSig),\n _orderParams.rssMetadata[4],\n _nonce\n )\n );\n }\n\n function _hashSig(Sig memory sig) internal pure returns (bytes32) {\n return keccak256(abi.encode(_SIGNATURE_TYPEHASH, sig.v, sig.r, sig.s));\n }\n\n function _hashOrder(Order memory order) internal pure returns (bytes32) {\n return\n keccak256(\n bytes.concat(\n abi.encode(\n _ORDER_TYPEHASH,\n order.exchange,\n order.maker,\n order.taker,\n order.makerRelayerFee,\n order.takerRelayerFee,\n order.makerProtocolFee,\n order.takerProtocolFee,\n order.feeRecipient,\n order.feeMethod,\n order.side,\n order.saleKind,\n order.target,\n order.howToCall\n ),\n abi.encode(\n keccak256(order.data),\n keccak256(order.replacementPattern),\n order.staticTarget,\n keccak256(order.staticExtradata),\n order.paymentToken,\n order.basePrice,\n order.extra,\n order.listingTime,\n order.expirationTime,\n order.salt\n )\n )\n );\n }\n\n function _exchange(BaseParams memory _baseParams, bytes memory _params) internal override {\n Params memory _orderParams = _decodeParams(_params);\n uint256 paymentValue = _baseParams.salePrice;\n if (_baseParams.currency == address(0)) {\n WETH.withdraw(paymentValue);\n openseaExchange.atomicMatch_{value: paymentValue}(\n _orderParams.addrs,\n _orderParams.uints,\n _orderParams.feeMethodsSidesKindsHowToCalls,\n _orderParams.calldataBuy,\n _orderParams.calldataSell,\n _orderParams.replacementPatternBuy,\n _orderParams.replacementPatternSell,\n _orderParams.staticExtradataBuy,\n _orderParams.staticExtradataSell,\n _orderParams.vs,\n _orderParams.rssMetadata\n );\n } else {\n WETH.approve(proxy, paymentValue);\n openseaExchange.atomicMatch_(\n _orderParams.addrs,\n _orderParams.uints,\n _orderParams.feeMethodsSidesKindsHowToCalls,\n _orderParams.calldataBuy,\n _orderParams.calldataSell,\n _orderParams.replacementPatternBuy,\n _orderParams.replacementPatternSell,\n _orderParams.staticExtradataBuy,\n _orderParams.staticExtradataSell,\n _orderParams.vs,\n _orderParams.rssMetadata\n );\n WETH.approve(proxy, 0);\n }\n }\n\n function _decodeParams(bytes memory _params) internal pure returns (Params memory) {\n return abi.decode(_params, (Params));\n }\n}\n" }, "contracts/interfaces/IOpenseaExchage.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\ninterface IOpenseaExchage {\n function tokenTransferProxy() external view returns (address);\n\n function registry() external view returns (address);\n\n function nonces(address owner) external view returns (uint256);\n\n function atomicMatch_(\n address[14] memory addrs,\n uint256[18] memory uints,\n uint8[8] memory feeMethodsSidesKindsHowToCalls,\n bytes memory calldataBuy,\n bytes memory calldataSell,\n bytes memory replacementPatternBuy,\n bytes memory replacementPatternSell,\n bytes memory staticExtradataBuy,\n bytes memory staticExtradataSell,\n uint8[2] memory vs,\n bytes32[5] memory rssMetadata\n ) external payable;\n}\n" }, "contracts/adapters/BaseAdapter.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\nimport {EIP712Upgradeable} from \"@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol\";\nimport {OwnableUpgradeable} from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport {PausableUpgradeable} from \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\nimport {ReentrancyGuardUpgradeable} from \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\nimport {IERC721Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\nimport {ERC721HolderUpgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol\";\nimport {IERC20Upgradeable, SafeERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport {SignatureCheckerUpgradeable} from \"@openzeppelin/contracts-upgradeable/utils/cryptography/SignatureCheckerUpgradeable.sol\";\n\nimport {IAaveFlashLoanReceiver} from \"../interfaces/IAaveFlashLoanReceiver.sol\";\nimport {ILendPool} from \"../interfaces/ILendPool.sol\";\nimport {PercentageMath} from \"../libraries/PercentageMath.sol\";\nimport {IWETH} from \"../interfaces/IWETH.sol\";\nimport {IDownpayment} from \"../interfaces/IDownpayment.sol\";\nimport {IENSReverseRegistrar} from \"../interfaces/IENSReverseRegistrar.sol\";\n\nabstract contract BaseAdapter is\n IAaveFlashLoanReceiver,\n OwnableUpgradeable,\n PausableUpgradeable,\n ReentrancyGuardUpgradeable,\n EIP712Upgradeable,\n ERC721HolderUpgradeable\n{\n using SafeERC20Upgradeable for IERC20Upgradeable;\n using PercentageMath for uint256;\n event Purchased(\n address indexed buyer,\n address indexed nftToken,\n uint256 nftTokenId,\n address indexed currency,\n uint256 borrowedAmount,\n uint256 price,\n uint256 flashLoanFee,\n uint256 downpaymentFee,\n bytes32 orderHash\n );\n IDownpayment public downpayment;\n IWETH public WETH;\n uint256[43] private __gap;\n\n function __BaseAdapter_init(\n string memory _name,\n string memory _version,\n address _downpayment\n ) internal onlyInitializing {\n __Ownable_init();\n __Pausable_init();\n __ReentrancyGuard_init();\n __EIP712_init(_name, _version);\n downpayment = IDownpayment(_downpayment);\n WETH = downpayment.WETH();\n }\n\n struct BaseParams {\n address nftAsset;\n uint256 nftTokenId;\n address currency;\n uint256 salePrice;\n bytes32 paramsHash;\n }\n struct LocalVars {\n address buyer;\n uint256 bendFeeAmount;\n uint256 buyerPayment;\n uint256 flashBorrowedAmount;\n uint256 flashFee;\n uint256 flashLoanDebt;\n uint256 nonce;\n bytes params;\n uint8 v;\n bytes32 r;\n bytes32 s;\n }\n\n // external functions\n function executeOperation(\n address[] calldata _assets,\n uint256[] calldata _amounts,\n uint256[] calldata _premiums,\n address _initiator,\n bytes calldata _params\n ) external override nonReentrant whenNotPaused returns (bool) {\n require(msg.sender == address(downpayment.getAaveLendPool()), \"Adapter: caller must be aave lending pool\");\n require(_initiator == address(downpayment), \"Adapter: flashloan initiator must be downpayment\");\n uint256 fee = downpayment.getFee(address(this));\n require(\n _assets.length == 1 && _amounts.length == 1 && _premiums.length == 1,\n \"Adapter: multiple assets not supported\"\n );\n require(_assets[0] == address(WETH), \"Adapter: only WETH borrowing allowed\");\n LocalVars memory vars;\n (vars.params, vars.buyer, vars.v, vars.r, vars.s) = abi.decode(\n _params,\n (bytes, address, uint8, bytes32, bytes32)\n );\n\n vars.flashBorrowedAmount = _amounts[0];\n vars.flashFee = _premiums[0];\n vars.nonce = downpayment.nonces(vars.buyer);\n\n BaseParams memory baseParams = _checkParams(\n vars.buyer,\n vars.flashBorrowedAmount,\n vars.flashFee,\n vars.params,\n vars.nonce\n );\n _checkSig(vars.buyer, baseParams.paramsHash, vars.v, vars.r, vars.s);\n\n require(vars.flashBorrowedAmount <= WETH.balanceOf(address(this)), \"Adapter: insufficient flash loan\");\n\n // Check if the flash loan can be paid off and payment sufficient\n vars.bendFeeAmount = baseParams.salePrice.percentMul(fee);\n\n vars.buyerPayment = vars.bendFeeAmount + vars.flashFee + baseParams.salePrice - vars.flashBorrowedAmount;\n require(\n WETH.balanceOf(vars.buyer) >= vars.buyerPayment &&\n WETH.allowance(vars.buyer, address(this)) >= vars.buyerPayment,\n \"Adapter: WETH Insufficient\"\n );\n\n vars.flashLoanDebt = vars.flashBorrowedAmount + vars.flashFee;\n\n // Prepare ETH, need buyer approve WETH to this contract\n if (vars.buyerPayment > 0) {\n IERC20Upgradeable(address(WETH)).safeTransferFrom(vars.buyer, address(this), vars.buyerPayment);\n }\n\n // Do exchange\n _exchange(baseParams, vars.params);\n\n _beforeBorrowWETH(baseParams.nftAsset, baseParams.nftTokenId, vars.buyer, vars.flashBorrowedAmount);\n\n // Borrow WETH from bend, need buyer approve NFT to this contract\n _borrowWETH(baseParams.nftAsset, baseParams.nftTokenId, vars.buyer, vars.flashBorrowedAmount);\n\n _afterBorrowWETH(baseParams.nftAsset, baseParams.nftTokenId, vars.buyer, vars.flashBorrowedAmount);\n\n // Charge fee, sent to bend collector\n _chargeFee(vars.bendFeeAmount);\n\n // Repay flash loan\n _repayFlashLoan(vars.flashLoanDebt);\n\n emit Purchased(\n vars.buyer,\n baseParams.nftAsset,\n baseParams.nftTokenId,\n baseParams.currency,\n vars.flashBorrowedAmount,\n baseParams.salePrice,\n vars.flashFee,\n vars.bendFeeAmount,\n baseParams.paramsHash\n );\n return true;\n }\n\n function pause() external onlyOwner whenNotPaused {\n _pause();\n }\n\n function unpause() external onlyOwner whenPaused {\n _unpause();\n }\n\n function setENSName(address registrar, string memory name) external onlyOwner returns (bytes32) {\n return IENSReverseRegistrar(registrar).setName(name);\n }\n\n // abstract functions\n function _checkParams(\n address _buyer,\n uint256 _flashBorrowedAmount,\n uint256 _flashFee,\n bytes memory _params,\n uint256 _nonce\n ) internal view virtual returns (BaseParams memory);\n\n function _exchange(BaseParams memory baseParams, bytes memory _params) internal virtual;\n\n // internal functions\n function _chargeFee(uint256 _amount) internal {\n if (_amount > 0) {\n WETH.approve(address(downpayment.getBendLendPool()), _amount);\n downpayment.getBendLendPool().deposit(address(WETH), _amount, downpayment.getFeeCollector(), 0);\n WETH.approve(address(downpayment.getBendLendPool()), 0);\n }\n }\n\n function _beforeBorrowWETH(\n address _nftAsset,\n uint256 _nftTokenId,\n address _onBehalfOf,\n uint256 _amount\n ) internal virtual {}\n\n function _borrowWETH(\n address _nftAsset,\n uint256 _nftTokenId,\n address _onBehalfOf,\n uint256 _amount\n ) internal {\n ILendPool _pool = downpayment.getBendLendPool();\n address _reserveToken = address(WETH);\n IERC721Upgradeable _nftERC721 = IERC721Upgradeable(_nftAsset);\n require(_nftERC721.ownerOf(_nftTokenId) == address(this), \"Adapter: not own nft\");\n _nftERC721.approve(address(_pool), _nftTokenId);\n _pool.borrow(_reserveToken, _amount, _nftAsset, _nftTokenId, _onBehalfOf, 0);\n }\n\n function _afterBorrowWETH(\n address _nftAsset,\n uint256 _nftTokenId,\n address _onBehalfOf,\n uint256 _amount\n ) internal virtual {}\n\n function _repayFlashLoan(uint256 _flashLoanDebt) internal {\n address aaveLendPool = address(downpayment.getAaveLendPool());\n WETH.approve(aaveLendPool, 0);\n WETH.approve(aaveLendPool, _flashLoanDebt);\n }\n\n function _checkSig(\n address _signer,\n bytes32 paramsHash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal view {\n require(\n SignatureCheckerUpgradeable.isValidSignatureNow(\n _signer,\n _hashTypedDataV4(paramsHash),\n abi.encodePacked(r, s, v)\n ),\n \"Adapter: invalid signature\"\n );\n }\n\n /**\n * @dev Only WETH contract is allowed to transfer ETH here. Prevent other addresses to send Ether to this contract.\n */\n receive() external payable {\n require(msg.sender == address(WETH), \"Adapter: receive not allowed\");\n }\n}\n" }, "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./ECDSAUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,\n * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding\n * they need in their contracts using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * _Available since v3.4._\n *\n * @custom:storage-size 52\n */\nabstract contract EIP712Upgradeable is Initializable {\n /* solhint-disable var-name-mixedcase */\n bytes32 private _HASHED_NAME;\n bytes32 private _HASHED_VERSION;\n bytes32 private constant _TYPE_HASH = keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n /* solhint-enable var-name-mixedcase */\n\n /**\n * @dev Initializes the domain separator and parameter caches.\n *\n * The meaning of `name` and `version` is specified in\n * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:\n *\n * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n * - `version`: the current major version of the signing domain.\n *\n * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n * contract upgrade].\n */\n function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n __EIP712_init_unchained(name, version);\n }\n\n function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n bytes32 hashedName = keccak256(bytes(name));\n bytes32 hashedVersion = keccak256(bytes(version));\n _HASHED_NAME = hashedName;\n _HASHED_VERSION = hashedVersion;\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());\n }\n\n function _buildDomainSeparator(\n bytes32 typeHash,\n bytes32 nameHash,\n bytes32 versionHash\n ) private view returns (bytes32) {\n return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));\n }\n\n /**\n * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n * function returns the hash of the fully encoded EIP712 message for this domain.\n *\n * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n *\n * ```solidity\n * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n * keccak256(\"Mail(address to,string contents)\"),\n * mailTo,\n * keccak256(bytes(mailContents))\n * )));\n * address signer = ECDSA.recover(digest, signature);\n * ```\n */\n function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);\n }\n\n /**\n * @dev The hash of the name parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712NameHash() internal virtual view returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /**\n * @dev The hash of the version parameter for the EIP712 domain.\n *\n * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n * are a concern.\n */\n function _EIP712VersionHash() internal virtual view returns (bytes32) {\n return _HASHED_VERSION;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" }, "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal onlyInitializing {\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal onlyInitializing {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if 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 _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" }, "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n function __Pausable_init() internal onlyInitializing {\n __Pausable_init_unchained();\n }\n\n function __Pausable_init_unchained() internal onlyInitializing {\n _paused = false;\n }\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view virtual returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is not paused.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n modifier whenNotPaused() {\n require(!paused(), \"Pausable: paused\");\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n modifier whenPaused() {\n require(paused(), \"Pausable: not paused\");\n _;\n }\n\n /**\n * @dev Triggers stopped state.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" }, "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\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 ReentrancyGuardUpgradeable is Initializable {\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 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n function __ReentrancyGuard_init() internal onlyInitializing {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal onlyInitializing {\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 making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _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 _status = _NOT_ENTERED;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" }, "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\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) external view 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) external view returns (bool);\n}\n" }, "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721ReceiverUpgradeable.sol\";\nimport \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC721Receiver} interface.\n *\n * Accepts all token transfers.\n * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.\n */\ncontract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable {\n function __ERC721Holder_init() internal onlyInitializing {\n }\n\n function __ERC721Holder_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC721Receiver-onERC721Received}.\n *\n * Always returns `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address,\n address,\n uint256,\n bytes memory\n ) public virtual override returns (bytes4) {\n return this.onERC721Received.selector;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" }, "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable 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 IERC20Upgradeable 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 IERC20Upgradeable 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 IERC20Upgradeable 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 IERC20Upgradeable 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 /**\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(IERC20Upgradeable 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}\n" }, "@openzeppelin/contracts-upgradeable/utils/cryptography/SignatureCheckerUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./ECDSAUpgradeable.sol\";\nimport \"../AddressUpgradeable.sol\";\nimport \"../../interfaces/IERC1271Upgradeable.sol\";\n\n/**\n * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA\n * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like\n * Argent and Gnosis Safe.\n *\n * _Available since v4.1._\n */\nlibrary SignatureCheckerUpgradeable {\n /**\n * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the\n * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.\n *\n * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus\n * change through time. It could return true at block N and false at block N+1 (or the opposite).\n */\n function isValidSignatureNow(\n address signer,\n bytes32 hash,\n bytes memory signature\n ) internal view returns (bool) {\n (address recovered, ECDSAUpgradeable.RecoverError error) = ECDSAUpgradeable.tryRecover(hash, signature);\n if (error == ECDSAUpgradeable.RecoverError.NoError && recovered == signer) {\n return true;\n }\n\n (bool success, bytes memory result) = signer.staticcall(\n abi.encodeWithSelector(IERC1271Upgradeable.isValidSignature.selector, hash, signature)\n );\n return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271Upgradeable.isValidSignature.selector);\n }\n}\n" }, "contracts/interfaces/IAaveFlashLoanReceiver.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\n/**\n * @title IAaveFlashLoanReceiver interface\n * @notice Interface for the Aave fee IFlashLoanReceiver.\n * @author Bend\n * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract\n **/\ninterface IAaveFlashLoanReceiver {\n function executeOperation(\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata premiums,\n address initiator,\n bytes calldata params\n ) external returns (bool);\n}\n" }, "contracts/interfaces/ILendPool.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\nimport {ILendPoolAddressesProvider} from \"./ILendPoolAddressesProvider.sol\";\n\ninterface ILendPool {\n /**\n * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying bTokens.\n * - E.g. User deposits 100 USDC and gets in return 100 bUSDC\n * @param reserve The address of the underlying asset to deposit\n * @param amount The amount to be deposited\n * @param onBehalfOf The address that will receive the bTokens, same as msg.sender if the user\n * wants to receive them on his own wallet, or a different address if the beneficiary of bTokens\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 deposit(\n address reserve,\n uint256 amount,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower\n * already deposited enough collateral\n * - E.g. User borrows 100 USDC, receiving the 100 USDC in his wallet\n * and lock collateral asset in contract\n * @param reserveAsset The address of the underlying asset to borrow\n * @param amount The amount to be borrowed\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token ID of the underlying NFT used as collateral\n * @param onBehalfOf Address of the user who will receive the loan. 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 * @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 borrow(\n address reserveAsset,\n uint256 amount,\n address nftAsset,\n uint256 nftTokenId,\n address onBehalfOf,\n uint16 referralCode\n ) external;\n\n /**\n * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent loan owned\n * - E.g. User repays 100 USDC, burning loan and receives collateral asset\n * @param nftAsset The address of the underlying NFT used as collateral\n * @param nftTokenId The token ID of the underlying NFT used as collateral\n * @param amount The amount to repay\n * @return The final amount repaid, loan is burned or not\n **/\n function repay(\n address nftAsset,\n uint256 nftTokenId,\n uint256 amount\n ) external returns (uint256, bool);\n\n /**\n * @dev Returns the loan data of the NFT\n * @param nftAsset The address of the NFT\n * @param reserveAsset The address of the Reserve\n * @return totalCollateralInETH the total collateral in ETH of the NFT\n * @return totalCollateralInReserve the total collateral in Reserve of the NFT\n * @return availableBorrowsInETH the borrowing power in ETH of the NFT\n * @return availableBorrowsInReserve the borrowing power in Reserve of the NFT\n * @return ltv the loan to value of the user\n * @return liquidationThreshold the liquidation threshold of the NFT\n * @return liquidationBonus the liquidation bonus of the NFT\n **/\n function getNftCollateralData(address nftAsset, address reserveAsset)\n external\n view\n returns (\n uint256 totalCollateralInETH,\n uint256 totalCollateralInReserve,\n uint256 availableBorrowsInETH,\n uint256 availableBorrowsInReserve,\n uint256 ltv,\n uint256 liquidationThreshold,\n uint256 liquidationBonus\n );\n}\n" }, "contracts/libraries/PercentageMath.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\n/**\n * @title PercentageMath library\n * @author Bend\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 half up\n **/\n\nlibrary PercentageMath {\n uint256 public constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals\n uint256 public constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;\n uint256 public constant ONE_PERCENT = 1e2; //100, 1%\n uint256 public constant TEN_PERCENT = 1e3; //1000, 10%\n uint256 public constant ONE_THOUSANDTH_PERCENT = 1e1; //10, 0.1%\n uint256 public constant ONE_TEN_THOUSANDTH_PERCENT = 1; //1, 0.01%\n\n /**\n * @dev Executes a percentage multiplication\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 The percentage of value\n **/\n function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {\n if (value == 0 || percentage == 0) {\n return 0;\n }\n\n require(value <= (type(uint256).max - HALF_PERCENT) / percentage, \"MATH_MULTIPLICATION_OVERFLOW\");\n\n return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;\n }\n}\n" }, "contracts/interfaces/IWETH.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\ninterface IWETH {\n function deposit() external payable;\n\n function withdraw(uint256) external;\n\n function allowance(address, address) external view returns (uint256);\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 function transfer(address dst, uint256 wad) external returns (bool);\n\n function balanceOf(address) external view returns (uint256);\n}\n" }, "contracts/interfaces/IDownpayment.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\nimport {IWETH} from \"./IWETH.sol\";\nimport {ILendPool} from \"./ILendPool.sol\";\nimport {IAaveLendPool} from \"./IAaveLendPool.sol\";\n\ninterface IDownpayment {\n struct Sig {\n uint8 v;\n bytes32 r;\n bytes32 s;\n }\n\n function WETH() external view returns (IWETH);\n\n function getFee(address adapter) external view returns (uint256);\n\n function getFeeCollector() external view returns (address);\n\n function getBendLendPool() external view returns (ILendPool);\n\n function getAaveLendPool() external view returns (IAaveLendPool);\n\n function nonces(address owner) external view returns (uint256);\n\n function isAdapterWhitelisted(address adapter) external view returns (bool);\n\n function viewCountWhitelistedAdapters() external view returns (uint256);\n\n function viewWhitelistedAdapters(uint256 cursor, uint256 size) external view returns (address[] memory, uint256);\n\n function buy(\n address adapter,\n uint256 borrowAmount,\n bytes calldata data,\n Sig calldata sig\n ) external payable;\n\n function addAdapter(address adapter) external;\n\n function removeAdapter(address adapter) external;\n}\n" }, "contracts/interfaces/IENSReverseRegistrar.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\ninterface IENSReverseRegistrar {\n /**\n * @dev Sets the `name()` record for the reverse ENS record associated with\n * the calling account. First updates the resolver to the default reverse\n * resolver if necessary.\n * @param name The name to set for this address.\n * @return The ENS node hash of the reverse record.\n */\n function setName(string memory name) external returns (bytes32);\n}\n" }, "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV\n }\n\n function _throwError(RecoverError error) private pure {\n if (error == RecoverError.NoError) {\n return; // no error: do nothing\n } else if (error == RecoverError.InvalidSignature) {\n revert(\"ECDSA: invalid signature\");\n } else if (error == RecoverError.InvalidSignatureLength) {\n revert(\"ECDSA: invalid signature length\");\n } else if (error == RecoverError.InvalidSignatureS) {\n revert(\"ECDSA: invalid signature 's' value\");\n } else if (error == RecoverError.InvalidSignatureV) {\n revert(\"ECDSA: invalid signature 'v' value\");\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature` or error string. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n *\n * Documentation for signature generation:\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n // Check the signature length\n // - case 65: r,s,v signature (standard)\n // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._\n if (signature.length == 65) {\n bytes32 r;\n bytes32 s;\n uint8 v;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n return tryRecover(hash, v, r, s);\n } else if (signature.length == 64) {\n bytes32 r;\n bytes32 vs;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n assembly {\n r := mload(add(signature, 0x20))\n vs := mload(add(signature, 0x40))\n }\n return tryRecover(hash, r, vs);\n } else {\n return (address(0), RecoverError.InvalidSignatureLength);\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, signature);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n *\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n *\n * _Available since v4.3._\n */\n function tryRecover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address, RecoverError) {\n bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n uint8 v = uint8((uint256(vs) >> 255) + 27);\n return tryRecover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n *\n * _Available since v4.2._\n */\n function recover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n * `r` and `s` signature fields separately.\n *\n * _Available since v4.3._\n */\n function tryRecover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address, RecoverError) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n return (address(0), RecoverError.InvalidSignatureS);\n }\n if (v != 27 && v != 28) {\n return (address(0), RecoverError.InvalidSignatureV);\n }\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n if (signer == address(0)) {\n return (address(0), RecoverError.InvalidSignature);\n }\n\n return (signer, RecoverError.NoError);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from `s`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", StringsUpgradeable.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n" }, "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = _setInitializedVersion(1);\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n bool isTopLevelCall = _setInitializedVersion(version);\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(version);\n }\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n _setInitializedVersion(type(uint8).max);\n }\n\n function _setInitializedVersion(uint8 version) private returns (bool) {\n // If the contract is initializing we ignore whether _initialized is set in order to support multiple\n // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level\n // of initializers, because in other contexts the contract may have been reentered.\n if (_initializing) {\n require(\n version == 1 && !AddressUpgradeable.isContract(address(this)),\n \"Initializable: contract is already initialized\"\n );\n return false;\n } else {\n require(_initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n return true;\n }\n }\n}\n" }, "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\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) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n}\n" }, "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\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 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\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" }, "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" }, "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\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 IERC165Upgradeable {\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" }, "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\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 IERC721ReceiverUpgradeable {\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" }, "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\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(address indexed owner, address indexed spender, uint256 value);\n\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 `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external 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) external view 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 `from` to `to` 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 from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" }, "@openzeppelin/contracts-upgradeable/interfaces/IERC1271Upgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)\n\npragma solidity ^0.8.0;\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 IERC1271Upgradeable {\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}\n" }, "contracts/interfaces/ILendPoolAddressesProvider.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\n/**\n * @title LendPoolAddressesProvider contract\n * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles\n * - Acting also as factory of proxies and admin of those, so with right to change its implementations\n * - Owned by the Bend Governance\n * @author Bend\n **/\ninterface ILendPoolAddressesProvider {\n function getLendPool() external view returns (address);\n}\n" }, "contracts/interfaces/IAaveLendPool.sol": { "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity 0.8.9;\n\ninterface IAaveLendPool {\n /**\n * @dev Allows smartcontracts to access the liquidity of the pool within one transaction,\n * as long as the amount taken plus a fee is returned.\n * IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.\n * For further details please visit https://developers.aave.com\n * @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface\n * @param assets The addresses of the assets being flash-borrowed\n * @param amounts The amounts amounts being flash-borrowed\n * @param modes Types of the debt to open if the flash loan is not returned:\n * 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver\n * 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address\n * @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2\n * @param params Variadic packed params to pass to the receiver as extra information\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 flashLoan(\n address receiverAddress,\n address[] calldata assets,\n uint256[] calldata amounts,\n uint256[] calldata modes,\n address onBehalfOf,\n bytes calldata params,\n uint16 referralCode\n ) external;\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 888888 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} } }