From c53630afa691418b637cf6bedcf8aeef9cefcd59 Mon Sep 17 00:00:00 2001 From: Admazzola Date: Thu, 27 Mar 2025 15:38:11 -0400 Subject: [PATCH 1/6] added tests to repro the issue no target improved price estimation using a uniswap lib clean up lib fix deploy scripts update deploy script remove target folder add rust target folders to gitignore --- .gitignore | 4 + .../LenderCommitmentGroup_Smart.sol | 8 +- .../libraries/UniswapPricingLibraryV2.sol | 167 ++++++++++++++++++ .../uniswap_pricing_libraryV2.ts | 19 ++ ...4_upgrade_lender_groups_pricing_library.ts | 101 +++++++++++ packages/contracts/lib/forge-std | 2 +- .../UniswapPricingLibrary_Test.sol | 117 ++++++++++-- 7 files changed, 397 insertions(+), 21 deletions(-) create mode 100644 packages/contracts/contracts/libraries/UniswapPricingLibraryV2.sol create mode 100644 packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts create mode 100644 packages/contracts/deploy/upgrades/24_upgrade_lender_groups_pricing_library.ts diff --git a/.gitignore b/.gitignore index 416059a62..95d280fca 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,10 @@ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. **/node_modules + +# rust target folders +**/target + packages/contracts/generated packages/contracts/deployments/hardhat packages/contracts/deployments/tenderly diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol index 0f14ba1fc..0deed5b76 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol @@ -54,7 +54,7 @@ import { ILenderCommitmentGroup } from "../../../interfaces/ILenderCommitmentGro import { Payment } from "../../../TellerV2Storage.sol"; import {IUniswapPricingLibrary} from "../../../interfaces/IUniswapPricingLibrary.sol"; -import {UniswapPricingLibrary} from "../../../libraries/UniswapPricingLibrary.sol"; +import {UniswapPricingLibraryV2} from "../../../libraries/UniswapPricingLibraryV2.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; @@ -884,7 +884,7 @@ contract LenderCommitmentGroup_Smart is uint256 principalAmount ) public view virtual returns (uint256 collateralTokensAmountToMatchValue) { - uint256 pairPriceWithTwapFromOracle = UniswapPricingLibrary + uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2 .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes); @@ -908,7 +908,7 @@ contract LenderCommitmentGroup_Smart is IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes ) external view virtual returns (uint256 ) { - uint256 pairPriceWithTwapFromOracle = UniswapPricingLibrary + uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2 .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes); @@ -919,7 +919,7 @@ contract LenderCommitmentGroup_Smart is IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes ) external view virtual returns (uint256 ) { - uint256 pairPriceWithTwapFromOracle = UniswapPricingLibrary + uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2 .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes); diff --git a/packages/contracts/contracts/libraries/UniswapPricingLibraryV2.sol b/packages/contracts/contracts/libraries/UniswapPricingLibraryV2.sol new file mode 100644 index 000000000..2d31c5b9f --- /dev/null +++ b/packages/contracts/contracts/libraries/UniswapPricingLibraryV2.sol @@ -0,0 +1,167 @@ +pragma solidity >=0.8.0 <0.9.0; +// SPDX-License-Identifier: MIT + + + +import {IUniswapPricingLibrary} from "../interfaces/IUniswapPricingLibrary.sol"; + +import "@openzeppelin/contracts/utils/math/Math.sol"; + + +import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; + +// Libraries +import { MathUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol"; + +import "../interfaces/uniswap/IUniswapV3Pool.sol"; + +import "../libraries/uniswap/TickMath.sol"; +import "../libraries/uniswap/FixedPoint96.sol"; +import "../libraries/uniswap/FullMath.sol"; + + +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + +import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; + + +/* + +Only do decimal expansion if it is an ERC20 not anything else !! + +*/ + +library UniswapPricingLibraryV2 +{ + + uint256 constant STANDARD_EXPANSION_FACTOR = 1e18; + + + function getUniswapPriceRatioForPoolRoutes( + IUniswapPricingLibrary.PoolRouteConfig[] memory poolRoutes + ) public view returns (uint256 priceRatio) { + require(poolRoutes.length <= 2, "invalid pool routes length"); + + if (poolRoutes.length == 2) { + uint256 pool0PriceRatio = getUniswapPriceRatioForPool( + poolRoutes[0] + ); + + uint256 pool1PriceRatio = getUniswapPriceRatioForPool( + poolRoutes[1] + ); + + return + FullMath.mulDiv( + pool0PriceRatio, + pool1PriceRatio, + STANDARD_EXPANSION_FACTOR + ); + } else if (poolRoutes.length == 1) { + return getUniswapPriceRatioForPool(poolRoutes[0]); + } + + //else return 0 + } + + /* + The resultant product is expanded by STANDARD_EXPANSION_FACTOR one time + */ + function getUniswapPriceRatioForPool( + IUniswapPricingLibrary.PoolRouteConfig memory _poolRouteConfig + ) public view returns (uint256 priceRatio) { + + + + // this is expanded by 2**96 or 1e28 + uint160 sqrtPriceX96 = getSqrtTwapX96( + _poolRouteConfig.pool, + _poolRouteConfig.twapInterval + ); + + + bool invert = ! _poolRouteConfig.zeroForOne; + + //this output will be expanded by 1e18 + return getQuoteFromSqrtRatioX96( sqrtPriceX96 , uint128( STANDARD_EXPANSION_FACTOR ), invert) ; + + + + } + + + //taken directly from uniswap oracle lib + /** + * @dev Calculates the amount of quote token received for a given amount of base token + * based on the square root of the price ratio (sqrtRatioX96). + * + * @param sqrtRatioX96 The square root of the price ratio(in terms of token1/token0) between two tokens, encoded as a Q64.96 value. + * @param baseAmount The amount of the base token for which the quote is to be calculated. Specify 1e18 for a price(quoteAmount) with 18 decimals of precision. + * @param inverse Specifies the direction of the price quote. If true then baseAmount must be the amount of token1, if false then baseAmount must be the amount for token0 + * + * @return quoteAmount The calculated amount of the quote token for the specified baseAmount + */ + + function getQuoteFromSqrtRatioX96( + uint160 sqrtRatioX96, + uint128 baseAmount, + bool inverse + ) internal pure returns (uint256 quoteAmount) { + // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself + if (sqrtRatioX96 <= type(uint128).max) { + uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; + quoteAmount = !inverse + ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) + : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); + } else { + uint256 ratioX128 = FullMath.mulDiv( + sqrtRatioX96, + sqrtRatioX96, + 1 << 64 + ); + quoteAmount = !inverse + ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) + : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); + } + } + + + function getSqrtTwapX96(address uniswapV3Pool, uint32 twapInterval) + internal + view + returns (uint160 sqrtPriceX96) + { + if (twapInterval == 0) { + // return the current price if twapInterval == 0 + (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0(); + } else { + uint32[] memory secondsAgos = new uint32[](2); + secondsAgos[0] = twapInterval + 1; // from (before) + secondsAgos[1] = 1; // one block prior + + (int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapV3Pool) + .observe(secondsAgos); + + // tick(imprecise as it's an integer) to price + sqrtPriceX96 = TickMath.getSqrtRatioAtTick( + int24( + (tickCumulatives[1] - tickCumulatives[0]) / + int32(twapInterval) + ) + ); + } + } + + function getPriceX96FromSqrtPriceX96(uint160 sqrtPriceX96) + internal + pure + returns (uint256 priceX96) + { + + + return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96); + } + +} \ No newline at end of file diff --git a/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts b/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts new file mode 100644 index 000000000..f39387a25 --- /dev/null +++ b/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts @@ -0,0 +1,19 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' + +const deployFn: DeployFunction = async (hre) => { + const { deployer } = await hre.getNamedAccounts() + const uniswapPricingLibraryV2 = await hre.deployments.deploy('UniswapPricingLibraryV2', { + from: deployer, + }) +} + +// tags and deployment +deployFn.id = 'teller-v2:uniswap-pricing-library-v2' +deployFn.tags = ['teller-v2', 'teller-v2:uniswap-pricing-library-v2'] +deployFn.dependencies = [''] + + +deployFn.skip = async (hre) => { + return !hre.network.live || !['sepolia', 'polygon' , 'base','arbitrum','mainnet','mainnet_live_fork'].includes(hre.network.name) +} +export default deployFn \ No newline at end of file diff --git a/packages/contracts/deploy/upgrades/24_upgrade_lender_groups_pricing_library.ts b/packages/contracts/deploy/upgrades/24_upgrade_lender_groups_pricing_library.ts new file mode 100644 index 000000000..5056a8e01 --- /dev/null +++ b/packages/contracts/deploy/upgrades/24_upgrade_lender_groups_pricing_library.ts @@ -0,0 +1,101 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' + +const deployFn: DeployFunction = async (hre) => { + hre.log('----------') + hre.log('') + hre.log('Lendergroups: Proposing upgrade...') + + + + const lenderCommitmentGroupBeaconProxy = await hre.contracts.get('LenderCommitmentGroupBeacon') + + const tellerV2 = await hre.contracts.get('TellerV2') + const SmartCommitmentForwarder = await hre.contracts.get( + 'SmartCommitmentForwarder' + ) + const tellerV2Address = await tellerV2.getAddress() + + const smartCommitmentForwarderAddress = + await SmartCommitmentForwarder.getAddress() + + let uniswapV3FactoryAddress: string + switch (hre.network.name) { + case 'mainnet': + case 'goerli': + case 'arbitrum': + case 'optimism': + case 'polygon': + case 'localhost': + uniswapV3FactoryAddress = '0x1F98431c8aD98523631AE4a59f267346ea31F984' + break + case 'base': + uniswapV3FactoryAddress = '0x33128a8fC17869897dcE68Ed026d694621f6FDfD' + break + case 'sepolia': + uniswapV3FactoryAddress = '0x0227628f3F023bb0B980b67D528571c95c6DaC1c' + break + default: + throw new Error('No swap factory address found for this network') + } + const uniswapPricingLibraryV2 = await hre.deployments.get('uniswapPricingLibraryV2') + + + +//this is why the owner of the beacon should be timelock controller ! +// so we can upgrade it like this . Using a proposal. This actually goes AROUND the proxy admin, interestingly. + await hre.upgrades.proposeBatchTimelock({ + title: 'LenderGroups: PoolOracle View', + description: ` +# LenderGroups + +* A patch to update the uniswap pricing library v2. +`, + _steps: [ + { + beacon: lenderCommitmentGroupBeaconProxy, + implFactory: await hre.ethers.getContractFactory('LenderCommitmentGroup_Smart', { + libraries: { + uniswapPricingLibraryV2: uniswapPricingLibraryV2.address, + }, + }), + + opts: { + // unsafeSkipStorageCheck: true, + unsafeAllow: [ + 'constructor', + 'state-variable-immutable', + 'external-library-linking', + ], + constructorArgs: [ + tellerV2Address, + smartCommitmentForwarderAddress, + uniswapV3FactoryAddress, + + ], + }, + }, + ], + }) + + hre.log('done.') + hre.log('') + hre.log('----------') + + return true +} + +// tags and deployment +deployFn.id = 'lender-commitment-group-beacon:upgrade-uniswap-price-lib-v2' +deployFn.tags = ['lender-commitment-group-beacon'] +deployFn.dependencies = [ + 'teller-v2:deploy', + 'teller-v2:uniswap-pricing-library-v2', + 'smart-commitment-forwarder:deploy', + 'teller-v2:uniswap-pricing-library', + 'lender-commitment-group-beacon:deploy' +] + +deployFn.skip = async (hre) => { + return !hre.network.live || !['sepolia','polygon'].includes(hre.network.name) +} +export default deployFn diff --git a/packages/contracts/lib/forge-std b/packages/contracts/lib/forge-std index 2f6762e4f..73a504d2c 160000 --- a/packages/contracts/lib/forge-std +++ b/packages/contracts/lib/forge-std @@ -1 +1 @@ -Subproject commit 2f6762e4f73f3d835457c220b5f62dfeeb6f6341 +Subproject commit 73a504d2cf6f37b7ce285b479f4c681f76e95f1b diff --git a/packages/contracts/tests/SmartCommitmentForwarder/UniswapPricingLibrary_Test.sol b/packages/contracts/tests/SmartCommitmentForwarder/UniswapPricingLibrary_Test.sol index 75f3756bb..28b70bd27 100644 --- a/packages/contracts/tests/SmartCommitmentForwarder/UniswapPricingLibrary_Test.sol +++ b/packages/contracts/tests/SmartCommitmentForwarder/UniswapPricingLibrary_Test.sol @@ -2,7 +2,7 @@ pragma solidity ^0.8.0; //import "forge-std/Test.sol"; -import "../../contracts/libraries/UniswapPricingLibrary.sol"; +import "../../contracts/libraries/UniswapPricingLibraryV2.sol"; import { Testable } from "../Testable.sol"; @@ -42,6 +42,85 @@ contract UniswapPricingLibraryTest is Testable { } + + function test_getUniswapPriceRatioForPool_high_price() public { + + bool zeroForOne = true; // ?? + + mockUniswapPool.set_mockSqrtPriceX96( 1e40 ); + + uint32 twapInterval = 0; + + IUniswapPricingLibrary.PoolRouteConfig + memory routeConfig = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPool(routeConfig); + + + + assertEq( 15930919111324522770288803977677118055911 , priceRatio , "unexpected price ratio") ; + } + + + function test_getUniswapPriceRatioForPool_low_price() public { + + bool zeroForOne = true; // ?? + + mockUniswapPool.set_mockSqrtPriceX96( 4295128739 ); + + uint32 twapInterval = 0; + + IUniswapPricingLibrary.PoolRouteConfig + memory routeConfig = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPool(routeConfig); + + + + // assertEq( 0 , priceRatio , "unexpected price ratio") ; + } + + function test_getUniswapPriceRatioForPool_very_low_price() public { + + bool zeroForOne = true; // ?? + + mockUniswapPool.set_mockSqrtPriceX96( 42959 ); + + uint32 twapInterval = 0; + + IUniswapPricingLibrary.PoolRouteConfig + memory routeConfig = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPool(routeConfig); + + + + // assertEq( 1e18 , priceRatio , "unexpected price ratio") ; + } + + + function test_getUniswapPriceRatioForPool_same_price() public { bool zeroForOne = false; // ?? @@ -59,7 +138,7 @@ contract UniswapPricingLibraryTest is Testable { token1Decimals: 18 }); - uint256 priceRatio = UniswapPricingLibrary + uint256 priceRatio = UniswapPricingLibraryV2 .getUniswapPriceRatioForPool(routeConfig); @@ -88,7 +167,7 @@ contract UniswapPricingLibraryTest is Testable { token1Decimals: 18 }); - uint256 priceRatio = UniswapPricingLibrary + uint256 priceRatio = UniswapPricingLibraryV2 .getUniswapPriceRatioForPool(routeConfig); @@ -121,7 +200,7 @@ contract UniswapPricingLibraryTest is Testable { token1Decimals: principalTokenDecimals }); - uint256 priceRatio = UniswapPricingLibrary + uint256 priceRatio = UniswapPricingLibraryV2 .getUniswapPriceRatioForPool(routeConfig); @@ -168,7 +247,7 @@ contract UniswapPricingLibraryTest is Testable { token1Decimals: principalTokenDecimals }); - uint256 priceRatio = UniswapPricingLibrary + uint256 priceRatio = UniswapPricingLibraryV2 .getUniswapPriceRatioForPoolRoutes(poolRoutes); console.log("price ratio"); @@ -214,7 +293,7 @@ contract UniswapPricingLibraryTest is Testable { token1Decimals: principalTokenDecimals }); - uint256 priceRatio = UniswapPricingLibrary + uint256 priceRatio = UniswapPricingLibraryV2 .getUniswapPriceRatioForPoolRoutes(poolRoutes); @@ -257,7 +336,7 @@ contract UniswapPricingLibraryTest is Testable { token1Decimals: 18 }); - uint256 priceRatio = UniswapPricingLibrary + uint256 priceRatio = UniswapPricingLibraryV2 .getUniswapPriceRatioForPoolRoutes(poolRoutes); console.log("price ratio"); @@ -288,7 +367,7 @@ contract UniswapPricingLibraryTest is Testable { token1Decimals: 18 }); - uint256 priceRatio = UniswapPricingLibrary + uint256 priceRatio = UniswapPricingLibraryV2 .getUniswapPriceRatioForPoolRoutes(poolRoutes); console.log("price ratio"); @@ -299,6 +378,12 @@ contract UniswapPricingLibraryTest is Testable { } +/* + Error: a == b not satisfied [uint] + Left: 1000000000000000000 + Right: 10000000000000000000000000000000000000000000000 + +*/ function test_getUniswapPriceRatioForPoolRoutes_price_scenario_C() public { mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); @@ -319,7 +404,7 @@ contract UniswapPricingLibraryTest is Testable { token1Decimals: 18 }); - uint256 priceRatio = UniswapPricingLibrary + uint256 priceRatio = UniswapPricingLibraryV2 .getUniswapPriceRatioForPoolRoutes(poolRoutes); console.log("price ratio"); @@ -351,7 +436,7 @@ contract UniswapPricingLibraryTest is Testable { token1Decimals: 18 }); - uint256 priceRatio = UniswapPricingLibrary + uint256 priceRatio = UniswapPricingLibraryV2 .getUniswapPriceRatioForPoolRoutes(poolRoutes); console.log("price ratio"); @@ -360,7 +445,7 @@ contract UniswapPricingLibraryTest is Testable { uint256 principalAmount = 1000; - assertEq( 953702069891996282433059426929 , priceRatio , "unexpected price ratio") ; + assertEq( 953702069890566199069022917957 , priceRatio , "unexpected price ratio") ; } @@ -383,7 +468,7 @@ function test_getUniswapPriceRatioForPool_zeroPrice() public { }); vm.expectRevert(); - uint256 priceRatio = UniswapPricingLibrary.getUniswapPriceRatioForPool(routeConfig) ; + uint256 priceRatio = UniswapPricingLibraryV2.getUniswapPriceRatioForPool(routeConfig) ; } function test_getUniswapPriceRatioForPool_largePrice() public { @@ -401,7 +486,7 @@ function test_getUniswapPriceRatioForPool_largePrice() public { token1Decimals: 18 }); - uint256 priceRatio = UniswapPricingLibrary.getUniswapPriceRatioForPool(routeConfig); + uint256 priceRatio = UniswapPricingLibraryV2.getUniswapPriceRatioForPool(routeConfig); assertEq( priceRatio, 0 , "unexpected price ratio") ; @@ -423,7 +508,7 @@ function test_getUniswapPriceRatioForPool_invalidDecimals() public { token1Decimals: 18 }); - uint256 priceRatio = UniswapPricingLibrary.getUniswapPriceRatioForPool(routeConfig) ; + uint256 priceRatio = UniswapPricingLibraryV2.getUniswapPriceRatioForPool(routeConfig) ; @@ -447,7 +532,7 @@ function test_getUniswapPriceRatioForPool_twapInterval() public { token1Decimals: 18 }); - uint256 priceRatio = UniswapPricingLibrary.getUniswapPriceRatioForPool(routeConfig); + uint256 priceRatio = UniswapPricingLibraryV2.getUniswapPriceRatioForPool(routeConfig); assert(priceRatio > 0); } @@ -481,7 +566,7 @@ function test_getUniswapPriceRatioForPoolRoutes_twoPools_differentPrices() publi token1Decimals: 18 }); - uint256 priceRatio = UniswapPricingLibrary.getUniswapPriceRatioForPoolRoutes(poolRoutes); + uint256 priceRatio = UniswapPricingLibraryV2.getUniswapPriceRatioForPoolRoutes(poolRoutes); //calculatet this more intelligently uint256 expectedPriceRatio = 15625000000000000; From 51070169d6f91723a180b2967a276e546f8e7b8c Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 3 Apr 2025 15:17:30 -0400 Subject: [PATCH 2/6] lcfa u2 tests pass --- .../LenderCommitmentForwarderAlpha.sol | 6 +- .../LenderCommitmentForwarder_U2.sol | 893 +++++++++++ .../ILenderCommitmentForwarder_U2.sol | 110 ++ .../25_upgrade_lcfa_pricing_library.ts | 114 ++ packages/contracts/lib/forge-std | 2 +- ...entForwarder_OracleLimited_U2_Override.sol | 87 ++ ...ntForwarder_OracleLimited_U2_Unit_Test.sol | 1367 +++++++++++++++++ 7 files changed, 2575 insertions(+), 4 deletions(-) create mode 100644 packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol create mode 100644 packages/contracts/contracts/interfaces/ILenderCommitmentForwarder_U2.sol create mode 100644 packages/contracts/deploy/upgrades/25_upgrade_lcfa_pricing_library.ts create mode 100644 packages/contracts/tests/LenderCommitmentForwarder/LenderCommitmentForwarder_OracleLimited_U2_Override.sol create mode 100644 packages/contracts/tests/LenderCommitmentForwarder/LenderCommitmentForwarder_OracleLimited_U2_Unit_Test.sol diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol b/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol index 61d33de97..936eb06a4 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol @@ -1,15 +1,15 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; -import "./LenderCommitmentForwarder_U1.sol"; +import "./LenderCommitmentForwarder_U2.sol"; -contract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U1 { +contract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U2 { constructor( address _tellerV2, address _marketRegistry, address _uniswapV3Factory ) - LenderCommitmentForwarder_U1( + LenderCommitmentForwarder_U2( _tellerV2, _marketRegistry, _uniswapV3Factory diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol b/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol new file mode 100644 index 000000000..f9ebf18cb --- /dev/null +++ b/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol @@ -0,0 +1,893 @@ +pragma solidity >=0.8.0 <0.9.0; +// SPDX-License-Identifier: MIT + +// Contracts +import "../TellerV2MarketForwarder_G2.sol"; + +// Interfaces +import "../interfaces/ICollateralManager.sol"; +import "../interfaces/ILenderCommitmentForwarder_U2.sol"; +import "./extensions/ExtensionsContextUpgradeable.sol"; + +import "@openzeppelin/contracts/utils/math/Math.sol"; + +import { Collateral, CollateralType } from "../interfaces/escrow/ICollateralEscrowV1.sol"; + +import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; + +// Libraries +import { MathUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; +import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol"; + +import "../interfaces/uniswap/IUniswapV3Pool.sol"; +import "../interfaces/uniswap/IUniswapV3Factory.sol"; + + +import "../libraries/uniswap/TickMath.sol"; +import "../libraries/uniswap/FixedPoint96.sol"; +import "../libraries/uniswap/FullMath.sol"; + +import "../libraries/NumbersLib.sol"; + +import {UniswapPricingLibraryV2} from "../libraries/UniswapPricingLibraryV2.sol"; + + + +import "./extensions/ExtensionsContextUpgradeable.sol"; + +import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + + + +/* + +Only do decimal expansion if it is an ERC20 not anything else !! + +*/ + +contract LenderCommitmentForwarder_U2 is + ExtensionsContextUpgradeable, //this should always be first for upgradeability + TellerV2MarketForwarder_G2, + ILenderCommitmentForwarder_U2 +{ + using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; + using NumbersLib for uint256; + + // CommitmentId => commitment + mapping(uint256 => Commitment) public commitments; + + uint256 commitmentCount; + + //https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/utils/structs/EnumerableSetUpgradeable.sol + mapping(uint256 => EnumerableSetUpgradeable.AddressSet) + internal commitmentBorrowersList; + + //commitment id => amount + mapping(uint256 => uint256) public commitmentPrincipalAccepted; + + mapping(uint256 => IUniswapPricingLibrary.PoolRouteConfig[]) internal commitmentUniswapPoolRoutes; + + mapping(uint256 => uint16) internal commitmentPoolOracleLtvRatio; + + //does not take a storage slot + address immutable UNISWAP_V3_FACTORY; + + uint256 immutable STANDARD_EXPANSION_FACTOR = 1e18; + + /** + * @notice This event is emitted when a lender's commitment is created. + * @param lender The address of the lender. + * @param marketId The Id of the market the commitment applies to. + * @param lendingToken The address of the asset being committed. + * @param tokenAmount The amount of the asset being committed. + */ + event CreatedCommitment( + uint256 indexed commitmentId, + address lender, + uint256 marketId, + address lendingToken, + uint256 tokenAmount + ); + + /** + * @notice This event is emitted when a lender's commitment is updated. + * @param commitmentId The id of the commitment that was updated. + * @param lender The address of the lender. + * @param marketId The Id of the market the commitment applies to. + * @param lendingToken The address of the asset being committed. + * @param tokenAmount The amount of the asset being committed. + */ + event UpdatedCommitment( + uint256 indexed commitmentId, + address lender, + uint256 marketId, + address lendingToken, + uint256 tokenAmount + ); + + /** + * @notice This event is emitted when the allowed borrowers for a commitment is updated. + * @param commitmentId The id of the commitment that was updated. + */ + event UpdatedCommitmentBorrowers(uint256 indexed commitmentId); + + /** + * @notice This event is emitted when a lender's commitment has been deleted. + * @param commitmentId The id of the commitment that was deleted. + */ + event DeletedCommitment(uint256 indexed commitmentId); + + /** + * @notice This event is emitted when a lender's commitment is exercised for a loan. + * @param commitmentId The id of the commitment that was exercised. + * @param borrower The address of the borrower. + * @param tokenAmount The amount of the asset being committed. + * @param bidId The bid id for the loan from TellerV2. + */ + event ExercisedCommitment( + uint256 indexed commitmentId, + address borrower, + uint256 tokenAmount, + uint256 bidId + ); + + error InsufficientCommitmentAllocation( + uint256 allocated, + uint256 requested + ); + error InsufficientBorrowerCollateral(uint256 required, uint256 actual); + + /** Modifiers **/ + + modifier commitmentLender(uint256 _commitmentId) { + require( + commitments[_commitmentId].lender == _msgSender(), + "unauthorized commitment lender" + ); + _; + } + + function validateCommitment(Commitment storage _commitment) internal { + require( + _commitment.expiration > uint32(block.timestamp), + "expired commitment" + ); + require( + _commitment.maxPrincipal > 0, + "commitment principal allocation 0" + ); + + if (_commitment.collateralTokenType != CommitmentCollateralType.NONE) { + require( + _commitment.maxPrincipalPerCollateralAmount > 0, + "commitment collateral ratio 0" + ); + + if ( + _commitment.collateralTokenType == + CommitmentCollateralType.ERC20 + ) { + require( + _commitment.collateralTokenId == 0, + "commitment collateral token id must be 0 for ERC20" + ); + } + } + } + + /** External Functions **/ + + /// @custom:oz-upgrades-unsafe-allow constructor + constructor( + address _protocolAddress, + address _marketRegistry, + address _uniswapV3Factory + ) TellerV2MarketForwarder_G2(_protocolAddress, _marketRegistry) { + UNISWAP_V3_FACTORY = _uniswapV3Factory; + } + + /** + * @notice Creates a loan commitment from a lender for a market. + * @param _commitment The new commitment data expressed as a struct + * @param _borrowerAddressList The array of borrowers that are allowed to accept loans using this commitment + * @return commitmentId_ returns the commitmentId for the created commitment + */ + function createCommitmentWithUniswap( + Commitment calldata _commitment, + address[] calldata _borrowerAddressList, + IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolRoutes, + uint16 _poolOracleLtvRatio //generally always between 0 and 100 % , 0 to 10000 + ) public returns (uint256 commitmentId_) { + commitmentId_ = commitmentCount++; + + require( + _commitment.lender == _msgSender(), + "unauthorized commitment creator" + ); + + commitments[commitmentId_] = _commitment; + + require(_poolRoutes.length == 0 || _commitment.collateralTokenType == CommitmentCollateralType.ERC20 , "can only use pool routes with ERC20 collateral"); + + + //routes length of 0 means ignore price oracle limits + require(_poolRoutes.length <= 2, "invalid pool routes length"); + + + + + for (uint256 i = 0; i < _poolRoutes.length; i++) { + commitmentUniswapPoolRoutes[commitmentId_].push(_poolRoutes[i]); + } + + commitmentPoolOracleLtvRatio[commitmentId_] = _poolOracleLtvRatio; + + //make sure the commitment data adheres to required specifications and limits + validateCommitment(commitments[commitmentId_]); + + //the borrower allowlists is in a different storage space so we append them to the array with this method s + _addBorrowersToCommitmentAllowlist(commitmentId_, _borrowerAddressList); + + emit CreatedCommitment( + commitmentId_, + _commitment.lender, + _commitment.marketId, + _commitment.principalTokenAddress, + _commitment.maxPrincipal + ); + } + + /** + * @notice Updates the commitment of a lender to a market. + * @param _commitmentId The Id of the commitment to update. + * @param _commitment The new commitment data expressed as a struct + */ + function updateCommitment( + uint256 _commitmentId, + Commitment calldata _commitment + ) public commitmentLender(_commitmentId) { + require( + _commitment.lender == _msgSender(), + "Commitment lender cannot be updated." + ); + + require( + _commitment.principalTokenAddress == + commitments[_commitmentId].principalTokenAddress, + "Principal token address cannot be updated." + ); + require( + _commitment.marketId == commitments[_commitmentId].marketId, + "Market Id cannot be updated." + ); + + commitments[_commitmentId] = _commitment; + + //make sure the commitment data still adheres to required specifications and limits + validateCommitment(commitments[_commitmentId]); + + emit UpdatedCommitment( + _commitmentId, + _commitment.lender, + _commitment.marketId, + _commitment.principalTokenAddress, + _commitment.maxPrincipal + ); + } + + /** + * @notice Updates the borrowers allowed to accept a commitment + * @param _commitmentId The Id of the commitment to update. + * @param _borrowerAddressList The array of borrowers that are allowed to accept loans using this commitment + */ + function addCommitmentBorrowers( + uint256 _commitmentId, + address[] calldata _borrowerAddressList + ) public commitmentLender(_commitmentId) { + _addBorrowersToCommitmentAllowlist(_commitmentId, _borrowerAddressList); + } + + /** + * @notice Updates the borrowers allowed to accept a commitment + * @param _commitmentId The Id of the commitment to update. + * @param _borrowerAddressList The array of borrowers that are allowed to accept loans using this commitment + */ + function removeCommitmentBorrowers( + uint256 _commitmentId, + address[] calldata _borrowerAddressList + ) public commitmentLender(_commitmentId) { + _removeBorrowersFromCommitmentAllowlist( + _commitmentId, + _borrowerAddressList + ); + } + + /** + * @notice Adds a borrower to the allowlist for a commmitment. + * @param _commitmentId The id of the commitment that will allow the new borrower + * @param _borrowerArray the address array of the borrowers that will be allowed to accept loans using the commitment + */ + function _addBorrowersToCommitmentAllowlist( + uint256 _commitmentId, + address[] calldata _borrowerArray + ) internal { + for (uint256 i = 0; i < _borrowerArray.length; i++) { + commitmentBorrowersList[_commitmentId].add(_borrowerArray[i]); + } + emit UpdatedCommitmentBorrowers(_commitmentId); + } + + /** + * @notice Removes a borrower to the allowlist for a commmitment. + * @param _commitmentId The id of the commitment that will allow the new borrower + * @param _borrowerArray the address array of the borrowers that will be allowed to accept loans using the commitment + */ + function _removeBorrowersFromCommitmentAllowlist( + uint256 _commitmentId, + address[] calldata _borrowerArray + ) internal { + for (uint256 i = 0; i < _borrowerArray.length; i++) { + commitmentBorrowersList[_commitmentId].remove(_borrowerArray[i]); + } + emit UpdatedCommitmentBorrowers(_commitmentId); + } + + /** + * @notice Removes the commitment of a lender to a market. + * @param _commitmentId The id of the commitment to delete. + */ + function deleteCommitment(uint256 _commitmentId) + public + commitmentLender(_commitmentId) + { + delete commitments[_commitmentId]; + delete commitmentBorrowersList[_commitmentId]; + emit DeletedCommitment(_commitmentId); + } + + /** + * @notice Accept the commitment to submitBid and acceptBid using the funds + * @dev LoanDuration must be longer than the market payment cycle + * @param _commitmentId The id of the commitment being accepted. + * @param _principalAmount The amount of currency to borrow for the loan. + * @param _collateralAmount The amount of collateral to use for the loan. + * @param _collateralTokenId The tokenId of collateral to use for the loan if ERC721 or ERC1155. + * @param _collateralTokenAddress The contract address to use for the loan collateral tokens. + * @param _recipient The address to receive the loan funds. + * @param _interestRate The interest rate APY to use for the loan in basis points. + * @param _loanDuration The overall duration for the loan. Must be longer than market payment cycle duration. + * @return bidId The ID of the loan that was created on TellerV2 + */ + function acceptCommitmentWithRecipient( + uint256 _commitmentId, + uint256 _principalAmount, + uint256 _collateralAmount, + uint256 _collateralTokenId, + address _collateralTokenAddress, + address _recipient, + uint16 _interestRate, + uint32 _loanDuration + ) public returns (uint256 bidId) { + require( + commitments[_commitmentId].collateralTokenType <= + CommitmentCollateralType.ERC1155_ANY_ID, + "Invalid commitment collateral type" + ); + + return + _acceptCommitment( + _commitmentId, + _principalAmount, + _collateralAmount, + _collateralTokenId, + _collateralTokenAddress, + _recipient, + _interestRate, + _loanDuration + ); + } + + function acceptCommitment( + uint256 _commitmentId, + uint256 _principalAmount, + uint256 _collateralAmount, + uint256 _collateralTokenId, + address _collateralTokenAddress, + uint16 _interestRate, + uint32 _loanDuration + ) public returns (uint256 bidId) { + return + acceptCommitmentWithRecipient( + _commitmentId, + _principalAmount, + _collateralAmount, + _collateralTokenId, + _collateralTokenAddress, + address(0), + _interestRate, + _loanDuration + ); + } + + /** + * @notice Accept the commitment to submitBid and acceptBid using the funds + * @dev LoanDuration must be longer than the market payment cycle + * @param _commitmentId The id of the commitment being accepted. + * @param _principalAmount The amount of currency to borrow for the loan. + * @param _collateralAmount The amount of collateral to use for the loan. + * @param _collateralTokenId The tokenId of collateral to use for the loan if ERC721 or ERC1155. + * @param _collateralTokenAddress The contract address to use for the loan collateral tokens. + * @param _recipient The address to receive the loan funds. + * @param _interestRate The interest rate APY to use for the loan in basis points. + * @param _loanDuration The overall duration for the loan. Must be longer than market payment cycle duration. + * @param _merkleProof An array of bytes32 which are the roots down the merkle tree, the merkle proof. + * @return bidId The ID of the loan that was created on TellerV2 + */ + function acceptCommitmentWithRecipientAndProof( + uint256 _commitmentId, + uint256 _principalAmount, + uint256 _collateralAmount, + uint256 _collateralTokenId, + address _collateralTokenAddress, + address _recipient, + uint16 _interestRate, + uint32 _loanDuration, + bytes32[] calldata _merkleProof + ) public returns (uint256 bidId) { + require( + commitments[_commitmentId].collateralTokenType == + CommitmentCollateralType.ERC721_MERKLE_PROOF || + commitments[_commitmentId].collateralTokenType == + CommitmentCollateralType.ERC1155_MERKLE_PROOF, + "Invalid commitment collateral type" + ); + + bytes32 _merkleRoot = bytes32( + commitments[_commitmentId].collateralTokenId + ); + bytes32 _leaf = keccak256(abi.encodePacked(_collateralTokenId)); + + //make sure collateral token id is a leaf within the proof + require( + MerkleProofUpgradeable.verifyCalldata( + _merkleProof, + _merkleRoot, + _leaf + ), + "Invalid proof" + ); + + return + _acceptCommitment( + _commitmentId, + _principalAmount, + _collateralAmount, + _collateralTokenId, + _collateralTokenAddress, + _recipient, + _interestRate, + _loanDuration + ); + } + + function acceptCommitmentWithProof( + uint256 _commitmentId, + uint256 _principalAmount, + uint256 _collateralAmount, + uint256 _collateralTokenId, + address _collateralTokenAddress, + uint16 _interestRate, + uint32 _loanDuration, + bytes32[] calldata _merkleProof + ) public returns (uint256 bidId) { + return + acceptCommitmentWithRecipientAndProof( + _commitmentId, + _principalAmount, + _collateralAmount, + _collateralTokenId, + _collateralTokenAddress, + address(0), + _interestRate, + _loanDuration, + _merkleProof + ); + } + + /** + * @notice Accept the commitment to submitBid and acceptBid using the funds + * @dev LoanDuration must be longer than the market payment cycle + * @param _commitmentId The id of the commitment being accepted. + * @param _principalAmount The amount of currency to borrow for the loan. + * @param _collateralAmount The amount of collateral to use for the loan. + * @param _collateralTokenId The tokenId of collateral to use for the loan if ERC721 or ERC1155. + * @param _collateralTokenAddress The contract address to use for the loan collateral tokens. + * @param _recipient The address to receive the loan funds. + * @param _interestRate The interest rate APY to use for the loan in basis points. + * @param _loanDuration The overall duration for the loan. Must be longer than market payment cycle duration. + * @return bidId The ID of the loan that was created on TellerV2 + */ + function _acceptCommitment( + uint256 _commitmentId, + uint256 _principalAmount, + uint256 _collateralAmount, + uint256 _collateralTokenId, + address _collateralTokenAddress, + address _recipient, + uint16 _interestRate, + uint32 _loanDuration + ) internal returns (uint256 bidId) { + Commitment storage commitment = commitments[_commitmentId]; + + //make sure the commitment data adheres to required specifications and limits + validateCommitment(commitment); + + //the collateral token of the commitment should be the same as the acceptor expects + require( + _collateralTokenAddress == commitment.collateralTokenAddress, + "Mismatching collateral token" + ); + + //the interest rate must be at least as high has the commitment demands. The borrower can use a higher interest rate although that would not be beneficial to the borrower. + require( + _interestRate >= commitment.minInterestRate, + "Invalid interest rate" + ); + //the loan duration must be less than the commitment max loan duration. The lender who made the commitment expects the money to be returned before this window. + require( + _loanDuration <= commitment.maxDuration, + "Invalid loan max duration" + ); + + require( + commitmentPrincipalAccepted[_commitmentId] <= commitment.maxPrincipal, + "Invalid loan max principal" + ); + + require( + commitmentBorrowersList[_commitmentId].length() == 0 || + commitmentBorrowersList[_commitmentId].contains(_msgSender()), + "unauthorized commitment borrower" + ); + + + //require that the borrower accepting the commitment cannot borrow more than the commitments max principal + if (_principalAmount > commitment.maxPrincipal) { + revert InsufficientCommitmentAllocation({ + allocated: commitment.maxPrincipal, + requested: _principalAmount + }); + } + + { + uint256 poolOraclePrice = UniswapPricingLibraryV2.getUniswapPriceRatioForPoolRoutes( + commitmentUniswapPoolRoutes[_commitmentId] + ); + + // bool usePoolRoutes = commitmentUniswapPoolRoutes[_commitmentId] .length > 0; + + //use the worst case ratio either the oracle or the static ratio + uint256 maxPrincipalPerCollateralAmount = (commitmentUniswapPoolRoutes[_commitmentId] .length > 0) // usePoolRoutes + ? Math.min( + poolOraclePrice .percent(commitmentPoolOracleLtvRatio[_commitmentId]) , + commitment.maxPrincipalPerCollateralAmount + ) + : commitment.maxPrincipalPerCollateralAmount; + + uint256 requiredCollateral = getRequiredCollateral( + _principalAmount, + maxPrincipalPerCollateralAmount, + commitment.collateralTokenType + ); + + if (_collateralAmount < requiredCollateral) { + revert InsufficientBorrowerCollateral({ + required: requiredCollateral, + actual: _collateralAmount + }); + } + } + + //ERC721 assets must have a quantity of 1 + if ( + commitment.collateralTokenType == CommitmentCollateralType.ERC721 || + commitment.collateralTokenType == + CommitmentCollateralType.ERC721_ANY_ID || + commitment.collateralTokenType == + CommitmentCollateralType.ERC721_MERKLE_PROOF + ) { + require( + _collateralAmount == 1, + "invalid commitment collateral amount for ERC721" + ); + } + + //ERC721 and ERC1155 types strictly enforce a specific token Id. ERC721_ANY and ERC1155_ANY do not. + if ( + commitment.collateralTokenType == CommitmentCollateralType.ERC721 || + commitment.collateralTokenType == CommitmentCollateralType.ERC1155 + ) { + require( + commitment.collateralTokenId == _collateralTokenId, + "invalid commitment collateral tokenId" + ); + } + + commitmentPrincipalAccepted[_commitmentId] += _principalAmount; + + require( + commitmentPrincipalAccepted[_commitmentId] <= + commitment.maxPrincipal, + "Exceeds max principal of commitment" + ); + + CreateLoanArgs memory createLoanArgs; + createLoanArgs.marketId = commitment.marketId; + createLoanArgs.lendingToken = commitment.principalTokenAddress; + createLoanArgs.principal = _principalAmount; + createLoanArgs.duration = _loanDuration; + createLoanArgs.interestRate = _interestRate; + createLoanArgs.recipient = _recipient; + if (commitment.collateralTokenType != CommitmentCollateralType.NONE) { + createLoanArgs.collateral = new Collateral[](1); + createLoanArgs.collateral[0] = Collateral({ + _collateralType: _getEscrowCollateralType( + commitment.collateralTokenType + ), + _tokenId: _collateralTokenId, + _amount: _collateralAmount, + _collateralAddress: commitment.collateralTokenAddress + }); + } + + bidId = _submitBidWithCollateral(createLoanArgs, _msgSender()); + + _acceptBid(bidId, commitment.lender); + + emit ExercisedCommitment( + _commitmentId, + _msgSender(), + _principalAmount, + bidId + ); + } + + /** + * @notice Calculate the amount of collateral required to borrow a loan with _principalAmount of principal + * @param _principalAmount The amount of currency to borrow for the loan. + * @param _maxPrincipalPerCollateralAmount The ratio for the amount of principal that can be borrowed for each amount of collateral. + * @param _collateralTokenType The type of collateral for the loan either ERC20, ERC721, ERC1155, or None. + + */ + function getRequiredCollateral( + uint256 _principalAmount, + uint256 _maxPrincipalPerCollateralAmount, + CommitmentCollateralType _collateralTokenType + ) public view virtual returns (uint256) { + if (_collateralTokenType == CommitmentCollateralType.NONE) { + return 0; + } + + if (_collateralTokenType == CommitmentCollateralType.ERC20) { + return + MathUpgradeable.mulDiv( + _principalAmount, + STANDARD_EXPANSION_FACTOR, + _maxPrincipalPerCollateralAmount, + MathUpgradeable.Rounding.Up + ); + } + + //for NFTs, do not use the uniswap expansion factor + return + MathUpgradeable.mulDiv( + _principalAmount, + 1, + _maxPrincipalPerCollateralAmount, + MathUpgradeable.Rounding.Up + ); + + + } + + /** + * @dev Returns the PoolRouteConfig at a specific index for a given commitmentId from the commitmentUniswapPoolRoutes mapping. + * @param commitmentId The commitmentId to access the mapping. + * @param index The index in the array of PoolRouteConfigs for the given commitmentId. + * @return The PoolRouteConfig at the specified index. + */ + function getCommitmentUniswapPoolRoute(uint256 commitmentId, uint index) + public + view + returns (IUniswapPricingLibrary.PoolRouteConfig memory) + { + require( + index < commitmentUniswapPoolRoutes[commitmentId].length, + "Index out of bounds" + ); + return commitmentUniswapPoolRoutes[commitmentId][index]; + } + + /** + * @dev Returns the entire array of PoolRouteConfigs for a given commitmentId from the commitmentUniswapPoolRoutes mapping. + * @param commitmentId The commitmentId to access the mapping. + * @return The entire array of PoolRouteConfigs for the specified commitmentId. + */ + function getAllCommitmentUniswapPoolRoutes(uint256 commitmentId) + public + view + returns (IUniswapPricingLibrary.PoolRouteConfig[] memory) + { + return commitmentUniswapPoolRoutes[commitmentId]; + } + + /** + * @dev Returns the uint16 value for a given commitmentId from the commitmentPoolOracleLtvRatio mapping. + * @param commitmentId The key to access the mapping. + * @return The uint16 value for the specified commitmentId. + */ + function getCommitmentPoolOracleLtvRatio(uint256 commitmentId) + public + view + returns (uint16) + { + return commitmentPoolOracleLtvRatio[commitmentId]; + } + + // ---- TWAP + + function getUniswapV3PoolAddress( + address _principalTokenAddress, + address _collateralTokenAddress, + uint24 _uniswapPoolFee + ) public view returns (address) { + return + IUniswapV3Factory(UNISWAP_V3_FACTORY).getPool( + _principalTokenAddress, + _collateralTokenAddress, + _uniswapPoolFee + ); + } + + + function getSqrtTwapX96(address uniswapV3Pool, uint32 twapInterval) + internal + view + returns (uint160 sqrtPriceX96) + { + if (twapInterval == 0) { + // return the current price if twapInterval == 0 + (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0(); + } else { + uint32[] memory secondsAgos = new uint32[](2); + secondsAgos[0] = twapInterval + 1; // from (before) + secondsAgos[1] = 1; // one block prior + + (int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapV3Pool) + .observe(secondsAgos); + + // tick(imprecise as it's an integer) to price + sqrtPriceX96 = TickMath.getSqrtRatioAtTick( + int24( + (tickCumulatives[1] - tickCumulatives[0]) / + int32(twapInterval) + ) + ); + } + } + + function getPriceX96FromSqrtPriceX96(uint160 sqrtPriceX96) + internal + pure + returns (uint256 priceX96) + { + return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96); + } + + // ----- + + /** + * @notice Return the array of borrowers that are allowlisted for a commitment + * @param _commitmentId The commitment id for the commitment to query. + * @return borrowers_ An array of addresses restricted to accept the commitment. Empty array means unrestricted. + */ + function getCommitmentBorrowers(uint256 _commitmentId) + external + view + returns (address[] memory borrowers_) + { + borrowers_ = commitmentBorrowersList[_commitmentId].values(); + } + + /** + * @notice Return the collateral type based on the commitmentcollateral type. Collateral type is used in the base lending protocol. + * @param _type The type of collateral to be used for the loan. + */ + function _getEscrowCollateralType(CommitmentCollateralType _type) + internal + pure + returns (CollateralType) + { + if (_type == CommitmentCollateralType.ERC20) { + return CollateralType.ERC20; + } + if ( + _type == CommitmentCollateralType.ERC721 || + _type == CommitmentCollateralType.ERC721_ANY_ID || + _type == CommitmentCollateralType.ERC721_MERKLE_PROOF + ) { + return CollateralType.ERC721; + } + if ( + _type == CommitmentCollateralType.ERC1155 || + _type == CommitmentCollateralType.ERC1155_ANY_ID || + _type == CommitmentCollateralType.ERC1155_MERKLE_PROOF + ) { + return CollateralType.ERC1155; + } + + revert("Unknown Collateral Type"); + } + + function getCommitmentMarketId(uint256 _commitmentId) + external + view + returns (uint256) + { + return commitments[_commitmentId].marketId; + } + + function getCommitmentLender(uint256 _commitmentId) + external + view + returns (address) + { + return commitments[_commitmentId].lender; + } + + function getCommitmentAcceptedPrincipal(uint256 _commitmentId) + external + view + returns (uint256) + { + return commitmentPrincipalAccepted[_commitmentId]; + } + + function getCommitmentMaxPrincipal(uint256 _commitmentId) + external + view + returns (uint256) + { + return commitments[_commitmentId].maxPrincipal; + } + + function getCommitmentPrincipalTokenAddress(uint256 _commitmentId) + external + view + returns (address) + { + return commitments[_commitmentId].principalTokenAddress; + } + + function getCommitmentCollateralTokenAddress(uint256 _commitmentId) + external + view + returns (address) + { + return commitments[_commitmentId].collateralTokenAddress; + } + + + + //Overrides + function _msgSender() + internal + view + virtual + override(ContextUpgradeable, ExtensionsContextUpgradeable) + returns (address sender) + { + return ExtensionsContextUpgradeable._msgSender(); + } +} diff --git a/packages/contracts/contracts/interfaces/ILenderCommitmentForwarder_U2.sol b/packages/contracts/contracts/interfaces/ILenderCommitmentForwarder_U2.sol new file mode 100644 index 000000000..79590512d --- /dev/null +++ b/packages/contracts/contracts/interfaces/ILenderCommitmentForwarder_U2.sol @@ -0,0 +1,110 @@ +// SPDX-Licence-Identifier: MIT +pragma solidity >=0.8.0 <0.9.0; + +import "./IUniswapPricingLibrary.sol"; + +interface ILenderCommitmentForwarder_U2 { + enum CommitmentCollateralType { + NONE, // no collateral required + ERC20, + ERC721, + ERC1155, + ERC721_ANY_ID, + ERC1155_ANY_ID, + ERC721_MERKLE_PROOF, + ERC1155_MERKLE_PROOF + } + + /** + * @notice Details about a lender's capital commitment. + * @param maxPrincipal Amount of tokens being committed by the lender. Max amount that can be loaned. + * @param expiration Expiration time in seconds, when the commitment expires. + * @param maxDuration Length of time, in seconds that the lender's capital can be lent out for. + * @param minInterestRate Minimum Annual percentage to be applied for loans using the lender's capital. + * @param collateralTokenAddress The address for the token contract that must be used to provide collateral for loans for this commitment. + * @param maxPrincipalPerCollateralAmount The amount of principal that can be used for a loan per each unit of collateral, expanded additionally by principal decimals. + * @param collateralTokenType The type of asset of the collateralTokenAddress (ERC20, ERC721, or ERC1155). + * @param lender The address of the lender for this commitment. + * @param marketId The market id for this commitment. + * @param principalTokenAddress The address for the token contract that will be used to provide principal for loans of this commitment. + */ + struct Commitment { + uint256 maxPrincipal; + uint32 expiration; + uint32 maxDuration; + uint16 minInterestRate; + address collateralTokenAddress; + uint256 collateralTokenId; //we use this for the MerkleRootHash for type ERC721_MERKLE_PROOF + uint256 maxPrincipalPerCollateralAmount; + CommitmentCollateralType collateralTokenType; + address lender; + uint256 marketId; + address principalTokenAddress; + } + + + // mapping(uint256 => Commitment) public commitments; + + function getCommitmentMarketId(uint256 _commitmentId) + external + view + returns (uint256); + + function getCommitmentLender(uint256 _commitmentId) + external + view + returns (address); + + function getCommitmentAcceptedPrincipal(uint256 _commitmentId) + external + view + returns (uint256); + + function getCommitmentMaxPrincipal(uint256 _commitmentId) + external + view + returns (uint256); + + function createCommitmentWithUniswap( + Commitment calldata _commitment, + address[] calldata _borrowerAddressList, + IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolRoutes, + uint16 _poolOracleLtvRatio + ) external returns (uint256); + + function acceptCommitmentWithRecipient( + uint256 _commitmentId, + uint256 _principalAmount, + uint256 _collateralAmount, + uint256 _collateralTokenId, + address _collateralTokenAddress, + address _recipient, + uint16 _interestRate, + uint32 _loanDuration + ) external returns (uint256 bidId_); + + function acceptCommitmentWithRecipientAndProof( + uint256 _commitmentId, + uint256 _principalAmount, + uint256 _collateralAmount, + uint256 _collateralTokenId, + address _collateralTokenAddress, + address _recipient, + uint16 _interestRate, + uint32 _loanDuration, + bytes32[] calldata _merkleProof + ) external returns (uint256 bidId_); + + + function getCommitmentPrincipalTokenAddress(uint256 _commitmentId) + external + view + returns (address); + + function getCommitmentCollateralTokenAddress(uint256 _commitmentId) + external + view + returns (address); + + +} diff --git a/packages/contracts/deploy/upgrades/25_upgrade_lcfa_pricing_library.ts b/packages/contracts/deploy/upgrades/25_upgrade_lcfa_pricing_library.ts new file mode 100644 index 000000000..dcb24f93b --- /dev/null +++ b/packages/contracts/deploy/upgrades/25_upgrade_lcfa_pricing_library.ts @@ -0,0 +1,114 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' + +const deployFn: DeployFunction = async (hre) => { + hre.log('----------') + hre.log('') + hre.log('LenderCommitmentForwarderAlpha: Proposing upgrade...') + + const chainId = await hre.getChainId() + + let uniswapFactoryAddress: string + switch (hre.network.name) { + case 'mainnet': + case 'goerli': + case 'arbitrum': + case 'optimism': + case 'polygon': + case 'localhost': + uniswapFactoryAddress = '0x1F98431c8aD98523631AE4a59f267346ea31F984' + break + case 'base': + uniswapFactoryAddress = '0x33128a8fC17869897dcE68Ed026d694621f6FDfD' + break + case 'sepolia': + uniswapFactoryAddress = '0x0227628f3F023bb0B980b67D528571c95c6DaC1c' + break + default: + throw new Error('No swap factory address found for this network') + } + + const tellerV2 = await hre.contracts.get('TellerV2') + + const marketRegistry = await hre.contracts.get('MarketRegistry') + + const lenderCommitmentForwarderAlpha = await hre.contracts.get( + 'LenderCommitmentForwarderAlpha' + ) + + const tellerV2ProxyAddress = await tellerV2.getAddress() + const marketRegistryProxyAddress = await marketRegistry.getAddress() + const lcfAlphaProxyAddress = await lenderCommitmentForwarderAlpha.getAddress() + + const uniswapPricingLibraryV2 = await hre.deployments.get('uniswapPricingLibraryV2') + + + const LenderCommitmentForwarderAlphaImplementation = + await hre.ethers.getContractFactory('LenderCommitmentForwarderAlpha', { + + + libraries: { + uniswapPricingLibraryV2: uniswapPricingLibraryV2.address, + }, + + + }) + + + + await hre.upgrades.proposeBatchTimelock({ + title: 'LenderCommitmentForwarderAlpha: Upgrade Fix 1', + description: ` +# LenderCommitmentForwarderAlpha + +* Upgrade to fix maxPrincipal require statement. +`, + _steps: [ + { + proxy: lcfAlphaProxyAddress, + implFactory: LenderCommitmentForwarderAlphaImplementation, + + opts: { + unsafeAllow: ['constructor', 'state-variable-immutable'], + + constructorArgs: [ + tellerV2ProxyAddress, + marketRegistryProxyAddress, + uniswapFactoryAddress, + ], + }, + }, + ], + }) + + + hre.log('done.') + hre.log('') + hre.log('----------') + + return true +} + +// tags and deployment +deployFn.id = 'lender-commitment-forwarder:alpha:upgrade_max_principal' +deployFn.tags = [ + 'proposal', + 'upgrade', + 'lender-commitment-forwarder:alpha', + 'lender-commitment-forwarder:alpha:upgrade_max_principal', +] +deployFn.dependencies = ['lender-commitment-forwarder:alpha:deploy'] +deployFn.skip = async (hre) => { + return ( + !hre.network.live || + ![ + 'localhost', + 'polygon', + 'arbitrum', + 'base', + 'mainnet', + 'sepolia' + + ].includes(hre.network.name) + ) +} +export default deployFn diff --git a/packages/contracts/lib/forge-std b/packages/contracts/lib/forge-std index 73a504d2c..2f6762e4f 160000 --- a/packages/contracts/lib/forge-std +++ b/packages/contracts/lib/forge-std @@ -1 +1 @@ -Subproject commit 73a504d2cf6f37b7ce285b479f4c681f76e95f1b +Subproject commit 2f6762e4f73f3d835457c220b5f62dfeeb6f6341 diff --git a/packages/contracts/tests/LenderCommitmentForwarder/LenderCommitmentForwarder_OracleLimited_U2_Override.sol b/packages/contracts/tests/LenderCommitmentForwarder/LenderCommitmentForwarder_OracleLimited_U2_Override.sol new file mode 100644 index 000000000..7e3104503 --- /dev/null +++ b/packages/contracts/tests/LenderCommitmentForwarder/LenderCommitmentForwarder_OracleLimited_U2_Override.sol @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "@openzeppelin/contracts/utils/Address.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "../../contracts/TellerV2MarketForwarder_G1.sol"; + +import "../../contracts/TellerV2Context.sol"; + +import { LenderCommitmentForwarder_U2 } from "../../contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol"; + +import { Collateral, CollateralType } from "../../contracts/interfaces/escrow/ICollateralEscrowV1.sol"; + +import { User } from "../Test_Helpers.sol"; + +import "../../contracts/mock/MarketRegistryMock.sol"; +import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol"; + +contract LenderCommitmentForwarder_U2_Override is LenderCommitmentForwarder_U2 { + bool public submitBidWasCalled; + bool public submitBidWithCollateralWasCalled; + bool public acceptBidWasCalled; + + constructor( + address tellerV2, + address marketRegistry, + address uniswapV3Factory + ) + LenderCommitmentForwarder_U2(tellerV2, marketRegistry, uniswapV3Factory) + {} + + function setCommitment(uint256 _commitmentId, Commitment memory _commitment) + public + { + commitments[_commitmentId] = _commitment; + } + + function _getEscrowCollateralTypeSuper(CommitmentCollateralType _type) + public + returns (CollateralType) + { + return super._getEscrowCollateralType(_type); + } + + function validateCommitmentSuper(uint256 _commitmentId) public { + super.validateCommitment(commitments[_commitmentId]); + } + + /* + Overrider methods + */ + + function _submitBidWithCollateral(CreateLoanArgs memory, address) + internal + override + returns (uint256 bidId) + { + submitBidWithCollateralWasCalled = true; + return 1; + } + + function _acceptBid(uint256, address) internal override returns (bool) { + acceptBidWasCalled = true; + + return true; + } +} + +contract LenderCommitmentForwarderTest_TellerV2Mock is TellerV2Context { + constructor() TellerV2Context(address(0)) {} + + function getSenderForMarket(uint256 _marketId) + external + view + returns (address) + { + return _msgSenderForMarket(_marketId); + } + + function getDataForMarket(uint256 _marketId) + external + view + returns (bytes calldata) + { + return _msgDataForMarket(_marketId); + } +} diff --git a/packages/contracts/tests/LenderCommitmentForwarder/LenderCommitmentForwarder_OracleLimited_U2_Unit_Test.sol b/packages/contracts/tests/LenderCommitmentForwarder/LenderCommitmentForwarder_OracleLimited_U2_Unit_Test.sol new file mode 100644 index 000000000..73e6d1097 --- /dev/null +++ b/packages/contracts/tests/LenderCommitmentForwarder/LenderCommitmentForwarder_OracleLimited_U2_Unit_Test.sol @@ -0,0 +1,1367 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "@openzeppelin/contracts/utils/Address.sol"; +import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; +import "../../contracts/TellerV2MarketForwarder_G1.sol"; + +import "../tokens/TestERC20Token.sol"; +import "../tokens/TestERC721Token.sol"; +import "../tokens/TestERC1155Token.sol"; +import "../../contracts/TellerV2Context.sol"; + +import { Testable } from "../Testable.sol"; + +import "../../contracts/interfaces/ILenderCommitmentForwarder.sol"; +import { LenderCommitmentForwarder_G2 } from "../../contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G2.sol"; + +import { Collateral, CollateralType } from "../../contracts/interfaces/escrow/ICollateralEscrowV1.sol"; + +import { User } from "../Test_Helpers.sol"; + +import "../../contracts/mock/MarketRegistryMock.sol"; + +import { LenderCommitmentForwarder_U2_Override } from "./LenderCommitmentForwarder_OracleLimited_U2_Override.sol"; +import { ILenderCommitmentForwarder_U2 } from "../../contracts/interfaces/ILenderCommitmentForwarder_U2.sol"; + +import { IUniswapPricingLibrary } from "../../contracts/interfaces/IUniswapPricingLibrary.sol"; +import { UniswapPricingLibraryV2 } from "../../contracts/libraries/UniswapPricingLibraryV2.sol"; + + + +import { UniswapV3PoolMock } from "../../contracts/mock/uniswap/UniswapV3PoolMock.sol"; + +import { UniswapV3FactoryMock } from "../../contracts/mock/uniswap/UniswapV3FactoryMock.sol"; + +import "../../contracts/libraries/uniswap/FullMath.sol"; + +import "forge-std/console.sol"; + +/* + + + // you have to do that to go from human prices to raw price ratios + // if zeroforone is true, the formula is : Pdec - Cdec + 18 + // if zeroforone is false, the formula is : Cdec - Pdec + 18 + + +*/ + + + + +contract LenderCommitmentForwarder_U2_Test is Testable { + LenderCommitmentForwarderTest_TellerV2Mock private tellerV2Mock; + MarketRegistryMock mockMarketRegistry; + + LenderCommitmentUser private marketOwner; + LenderCommitmentUser private lender; + LenderCommitmentUser private borrower; + + + + address[] emptyArray; + address[] borrowersArray; + + TestERC20Token principalToken; + uint8 principalTokenDecimals = 18; + + TestERC20Token collateralToken; + uint8 collateralTokenDecimals = 18; + + TestERC20Token intermediateToken; + uint8 intermediateTokenDecimals = 18; + + TestERC721Token erc721Token; + TestERC1155Token erc1155Token; + + LenderCommitmentForwarder_U2_Override lenderCommitmentForwarder; + + uint256 maxPrincipal; + uint32 expiration; + uint32 maxDuration; + uint16 minInterestRate; + // address collateralTokenAddress; + uint256 collateralTokenId; + uint256 maxPrincipalPerCollateralAmount; + ILenderCommitmentForwarder_U2.CommitmentCollateralType collateralTokenType; + + uint256 marketId; + + UniswapV3FactoryMock mockUniswapFactory; + UniswapV3PoolMock mockUniswapPool; + UniswapV3PoolMock mockUniswapPoolSecondary; + + // address principalTokenAddress; + + constructor() {} + + function setUp() public { + tellerV2Mock = new LenderCommitmentForwarderTest_TellerV2Mock(); + mockMarketRegistry = new MarketRegistryMock(); + + mockUniswapFactory = new UniswapV3FactoryMock(); + mockUniswapPool = new UniswapV3PoolMock(); + + mockUniswapPoolSecondary = new UniswapV3PoolMock(); + + lenderCommitmentForwarder = new LenderCommitmentForwarder_U2_Override( + address(tellerV2Mock), + address(mockMarketRegistry), + address(mockUniswapFactory) + ); + + marketOwner = new LenderCommitmentUser( + address(tellerV2Mock), + address(lenderCommitmentForwarder) + ); + borrower = new LenderCommitmentUser( + address(tellerV2Mock), + address(lenderCommitmentForwarder) + ); + lender = new LenderCommitmentUser( + address(tellerV2Mock), + address(lenderCommitmentForwarder) + ); + + + + tellerV2Mock.__setMarketRegistry(address(mockMarketRegistry)); + mockMarketRegistry.setMarketOwner(address(marketOwner)); + + //tokenAddress = address(0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174); + marketId = 2; + maxPrincipal = 100000000000000000000; + maxPrincipalPerCollateralAmount = 100; + maxDuration = 2480000; + minInterestRate = 3000; + expiration = uint32(block.timestamp) + uint32(64000); + + marketOwner.setTrustedMarketForwarder( + marketId, + address(lenderCommitmentForwarder) + ); + lender.approveMarketForwarder( + marketId, + address(lenderCommitmentForwarder) + ); + + borrowersArray = new address[](1); + borrowersArray[0] = address(borrower); + + principalToken = new TestERC20Token( + "Test Wrapped ETH", + "TWETH", + 0, + principalTokenDecimals + ); + + collateralToken = new TestERC20Token( + "Test USDC", + "TUSDC", + 0, + collateralTokenDecimals + ); + + erc721Token = new TestERC721Token("ERC721", "ERC721"); + + erc1155Token = new TestERC1155Token("Test 1155"); + } + + // yarn contracts test --match-test test_getUniswapPrice + + function test_getUniswapPriceRatioForPool_same_price() public { + //collateralTokenDecimals = 6; + + bool zeroForOne = false; // ?? + + mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); + + uint32 twapInterval = 0; + + IUniswapPricingLibrary.PoolRouteConfig + memory routeConfig = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPool(routeConfig); + + console.log("price ratio"); + console.logUint(priceRatio); + + /* + validate through this ... + + + ); + + + price ratio is + 100000000000000000000000000000000000000 + + + expFactor is + 10000000000000000000000000000000000000 + + so the math is... + + PA * expFactor / PR + + */ + + uint256 principalAmount = 1000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPool_different_price() public { + //collateralTokenDecimals = 6; + + bool zeroForOne = false; // ?? + + //i think this means the ratio is 100:1 + mockUniswapPool.set_mockSqrtPriceX96(10 * 2**96); + + uint32 twapInterval = 0; + + IUniswapPricingLibrary.PoolRouteConfig + memory routeConfig = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPool(routeConfig); + + console.log("price ratio"); + console.logUint(priceRatio); + + //uint256 priceRatioNormalized = FullMath.mulDiv(priceRatio,1,10**(principalTokenDecimals+collateralTokenDecimals)); + + uint256 principalAmount = 1000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 100000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPool_decimal_scenario_A() public { + bool zeroForOne = false; + + principalTokenDecimals = 18; + collateralTokenDecimals = 6; + + principalToken = new TestERC20Token( + "Test Wrapped ETH", + "TWETH", + 0, + principalTokenDecimals + ); + + collateralToken = new TestERC20Token( + "Test USDC", + "TUSDC", + 0, + collateralTokenDecimals + ); + + mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); + + uint32 twapInterval = 0; + + IUniswapPricingLibrary.PoolRouteConfig + memory routeConfig = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: collateralTokenDecimals, + token1Decimals: principalTokenDecimals + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPool(routeConfig); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPoolRoutes() public { + mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); + + mockUniswapPoolSecondary.set_mockSqrtPriceX96(1 * 2**96); + + uint32 twapInterval = 0; //for now + + bool zeroForOne = false; + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 2 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + poolRoutes[1] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPoolSecondary), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPoolRoutes_zeroforone() public { + mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); + + mockUniswapPoolSecondary.set_mockSqrtPriceX96(1 * 2**96); + + //collateralTokenDecimals = 6; + + uint32 twapInterval = 0; //for now + + bool zeroForOne = true; + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 2 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + poolRoutes[1] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPoolSecondary), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + + function test_getRequiredCollateral_NFT_scenario_A() public { + bool zeroForOne = false; + + principalTokenDecimals = 18; + collateralTokenDecimals = 6; + + principalToken = new TestERC20Token( + "Test Wrapped ETH", + "TWETH", + 0, + principalTokenDecimals + ); + + + + uint256 principalAmount = 1000; + maxPrincipalPerCollateralAmount = 5000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + maxPrincipalPerCollateralAmount, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC721 + ); + + assertEq(requiredCollateral, 1 , "unexpected required collateral"); + } + + function test_getRequiredCollateral_NFT_Scenario_B() public { + bool zeroForOne = false; + + principalTokenDecimals = 18; + collateralTokenDecimals = 6; + + principalToken = new TestERC20Token( + "Test Wrapped ETH", + "TWETH", + 0, + principalTokenDecimals + ); + + + + uint256 principalAmount = 100000; + maxPrincipalPerCollateralAmount = 5000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + maxPrincipalPerCollateralAmount, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC1155 + ); + + assertEq(requiredCollateral, 20 , "unexpected required collateral"); + } + + + // why does this fail ? + /* function test_getUniswapPriceRatioForPoolRoutes_decimal_scenario_A() public { + + + mockUniswapPool.set_mockSqrtPriceX96( 1 * 2**96 ); + + mockUniswapPoolSecondary.set_mockSqrtPriceX96( 1 * 2**96 ); + + + principalTokenDecimals = 18; + collateralTokenDecimals = 6; + + principalToken = new TestERC20Token( + "Test Wrapped ETH", + "TWETH", + 0, + principalTokenDecimals + ); + + collateralToken = new TestERC20Token( + "Test USDC", + "TUSDC", + 0, + collateralTokenDecimals + ); + + + + uint32 twapInterval = 0; //for now + + bool zeroForOne = false; + + + + + ILenderCommitmentForwarder_U2.PoolRouteConfig[] memory poolRoutes = new ILenderCommitmentForwarder_U2.PoolRouteConfig[](2); + + poolRoutes[0] = ILenderCommitmentForwarder_U2.PoolRouteConfig({ + + pool:address(mockUniswapPool), + zeroForOne:zeroForOne, + twapInterval:twapInterval, + token0Decimals:principalTokenDecimals, + token1Decimals:collateralTokenDecimals + }); + + poolRoutes[1] = ILenderCommitmentForwarder_U2.PoolRouteConfig({ + + pool:address(mockUniswapPoolSecondary), + zeroForOne:zeroForOne, + twapInterval:twapInterval, + token0Decimals:collateralTokenDecimals, + token1Decimals:principalTokenDecimals + }); + + + uint256 priceRatio = lenderCommitmentForwarder.getUniswapPriceRatioForPoolRoutes( + poolRoutes + ); + + console.log("price ratio"); + console.logUint(priceRatio); + + + uint256 principalAmount = 1000; + + uint256 requiredCollateral = lenderCommitmentForwarder.getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20, + address(collateralToken), + address(principalToken) + ); + + assertEq( requiredCollateral, 1000, "unexpected required collateral" ); + + + } + */ + + function test_getUniswapPriceRatioForPoolRoutes_decimal_scenario_A() + public + { + mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); + + mockUniswapPoolSecondary.set_mockSqrtPriceX96(1 * 2**96); + + uint32 twapInterval = 0; //for now + + bool zeroForOne = false; + + principalTokenDecimals = 18; + intermediateTokenDecimals = 18; + collateralTokenDecimals = 6; + + principalToken = new TestERC20Token( + "Test Wrapped ETH", + "TWETH", + 0, + principalTokenDecimals + ); + + collateralToken = new TestERC20Token( + "Test USDC", + "TUSDC", + 0, + collateralTokenDecimals + ); + + intermediateToken = new TestERC20Token( + "Test Intermediate", + "TINT", + 0, + intermediateTokenDecimals + ); + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 2 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: intermediateTokenDecimals, + token1Decimals: collateralTokenDecimals + }); + + poolRoutes[1] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPoolSecondary), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: principalTokenDecimals, + token1Decimals: intermediateTokenDecimals + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + //which decimals is this using any why? p / c / i ? + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPoolRoutes_decimal_scenario_A2() + public + { + mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); + + mockUniswapPoolSecondary.set_mockSqrtPriceX96(1 * 2**96); + + uint32 twapInterval = 0; //for now + + principalTokenDecimals = 18; + intermediateTokenDecimals = 18; + collateralTokenDecimals = 6; + + principalToken = new TestERC20Token( + "Test Wrapped ETH", + "TWETH", + 0, + principalTokenDecimals + ); + + collateralToken = new TestERC20Token( + "Test USDC", + "TUSDC", + 0, + collateralTokenDecimals + ); + + intermediateToken = new TestERC20Token( + "Test Intermediate", + "TINT", + 0, + intermediateTokenDecimals + ); + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 2 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: false, + twapInterval: twapInterval, + token0Decimals: intermediateTokenDecimals, + token1Decimals: collateralTokenDecimals + }); + + poolRoutes[1] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPoolSecondary), + zeroForOne: true, + twapInterval: twapInterval, + token0Decimals: intermediateTokenDecimals, + token1Decimals: principalTokenDecimals + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + //which decimals is this using any why? p / c / i ? + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPoolRoutes_decimal_scenario_B() + public + { + mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); + + mockUniswapPoolSecondary.set_mockSqrtPriceX96(1 * 2**96); + + uint32 twapInterval = 0; //for now + + bool zeroForOne = true; + + principalTokenDecimals = 18; + intermediateTokenDecimals = 18; + collateralTokenDecimals = 6; + + principalToken = new TestERC20Token( + "Test Wrapped ETH", + "TWETH", + 0, + principalTokenDecimals + ); + + collateralToken = new TestERC20Token( + "Test USDC", + "TUSDC", + 0, + collateralTokenDecimals + ); + + intermediateToken = new TestERC20Token( + "Test Intermediate", + "TINT", + 0, + intermediateTokenDecimals + ); + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 2 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: collateralTokenDecimals, + token1Decimals: intermediateTokenDecimals + }); + + poolRoutes[1] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPoolSecondary), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: intermediateTokenDecimals, + token1Decimals: principalTokenDecimals + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + //which decimals is this using any why? p / c / i ? + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPoolRoutes_decimal_scenario_C() + public + { + mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); + + mockUniswapPoolSecondary.set_mockSqrtPriceX96(1 * 2**96); + + uint32 twapInterval = 0; //for now + + bool zeroForOne = true; + + principalTokenDecimals = 6; + intermediateTokenDecimals = 18; + collateralTokenDecimals = 18; + + principalToken = new TestERC20Token( + "Test Wrapped ETH", + "TWETH", + 0, + principalTokenDecimals + ); + + collateralToken = new TestERC20Token( + "Test USDC", + "TUSDC", + 0, + collateralTokenDecimals + ); + + intermediateToken = new TestERC20Token( + "Test Intermediate", + "TINT", + 0, + intermediateTokenDecimals + ); + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 2 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: collateralTokenDecimals, + token1Decimals: intermediateTokenDecimals + }); + + poolRoutes[1] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPoolSecondary), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: intermediateTokenDecimals, + token1Decimals: principalTokenDecimals + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + // uint256 priceRatioNormalized = FullMath.mulDiv(priceRatio,1,10**(principalTokenDecimals+collateralTokenDecimals)); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + //which decimals is this using any why? p / c / i ? + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPoolRoutes_price_scenario_A() public { + mockUniswapPool.set_mockSqrtPriceX96(10 * 2**96); + + uint160 priceTwo = uint160(1 * 2**96) / uint160(10); + mockUniswapPoolSecondary.set_mockSqrtPriceX96(priceTwo); + + uint32 twapInterval = 0; //for now + + bool zeroForOne = false; + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 2 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + poolRoutes[1] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPoolSecondary), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPoolRoutes_price_scenario_B() public { + mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); + + uint32 twapInterval = 0; //for now + + bool zeroForOne = false; + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 1 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPoolRoutes_price_scenario_C() public { + mockUniswapPool.set_mockSqrtPriceX96(1 * 2**96); + + uint32 twapInterval = 0; //for now + + bool zeroForOne = true; + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 1 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq(requiredCollateral, 1000, "unexpected required collateral"); + } + + function test_getUniswapPriceRatioForPoolRoutes_price_scenario_D() public { + mockUniswapPool.set_mockSqrtPriceX96(81128457937705300000000); + + uint32 twapInterval = 0; //for now + + bool zeroForOne = false; + + //principal is usdc + //collateral is wmatic + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 1 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 6, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + uint256 requiredCollateral = lenderCommitmentForwarder + .getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq( + priceRatio, + 953702069890566199069022917957, + "unexpected price ratio" + ); + // assertEq( requiredCollateral, 1000, "unexpected required collateral" ); + } + + function test_getUniswapPriceRatioForPoolRoutes_price_scenario_E() public { + mockUniswapPool.set_mockSqrtPriceX96(81128457937705300000000); + + uint32 twapInterval = 0; //for now + + bool zeroForOne = true; + + //principal is usdc + //collateral is wmatic + + IUniswapPricingLibrary.PoolRouteConfig[] + memory poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 1 + ); + + poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 6, + token1Decimals: 18 + }); + + uint256 priceRatio = UniswapPricingLibraryV2 + .getUniswapPriceRatioForPoolRoutes(poolRoutes); + + console.log("price ratio"); + console.logUint(priceRatio); + + uint256 principalAmount = 1000; + + /* uint256 requiredCollateral = lenderCommitmentForwarder.getRequiredCollateral( + principalAmount, + priceRatio, + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + );*/ + + assertEq(priceRatio, 1048545, "unexpected price ratio"); + // assertEq( requiredCollateral, 1000, "unexpected required collateral" ); + } + + + function test_createCommitmentWithUniswap() public { + + + + + collateralTokenType = ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20; + + + ILenderCommitmentForwarder_U2.Commitment + memory _commitment = ILenderCommitmentForwarder_U2.Commitment({ + maxPrincipal: maxPrincipal, + expiration: expiration, + maxDuration: maxDuration, + minInterestRate: minInterestRate, + collateralTokenAddress: address(collateralToken), + collateralTokenId: collateralTokenId, + maxPrincipalPerCollateralAmount: maxPrincipalPerCollateralAmount, + collateralTokenType: collateralTokenType, + lender: address(lender), + marketId: marketId, + principalTokenAddress: address(principalToken) + }); + + // uint256 c_id = lender._createCommitment(c, emptyArray); + + address[] memory _borrowerAddressList ; + IUniswapPricingLibrary.PoolRouteConfig[] memory _poolRoutes ; + + vm.prank(address(lender)); + uint256 _commitmentId = lenderCommitmentForwarder + .createCommitmentWithUniswap( + _commitment, + _borrowerAddressList, + _poolRoutes, + 10000 + ); + + + } + + + function test_createCommitmentWithUniswap_two_routes() public { + + + + + collateralTokenType = ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20; + + + ILenderCommitmentForwarder_U2.Commitment + memory _commitment = ILenderCommitmentForwarder_U2.Commitment({ + maxPrincipal: maxPrincipal, + expiration: expiration, + maxDuration: maxDuration, + minInterestRate: minInterestRate, + collateralTokenAddress: address(collateralToken), + collateralTokenId: collateralTokenId, + maxPrincipalPerCollateralAmount: maxPrincipalPerCollateralAmount, + collateralTokenType: collateralTokenType, + lender: address(lender), + marketId: marketId, + principalTokenAddress: address(principalToken) + }); + + // uint256 c_id = lender._createCommitment(c, emptyArray); + + address[] memory _borrowerAddressList ; + + IUniswapPricingLibrary.PoolRouteConfig[] + memory _poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 2 + ); + + bool zeroForOne = false; + uint32 twapInterval = 10; + + _poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + _poolRoutes[1] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPoolSecondary), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + vm.prank(address(lender)); + uint256 _commitmentId = lenderCommitmentForwarder + .createCommitmentWithUniswap( + _commitment, + _borrowerAddressList, + _poolRoutes, + 10000 + ); + + + } + + + function test_createCommitmentWithUniswap_two_routes_invalid_type() public { + + + + + collateralTokenType = ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC721; + + + ILenderCommitmentForwarder_U2.Commitment + memory _commitment = ILenderCommitmentForwarder_U2.Commitment({ + maxPrincipal: maxPrincipal, + expiration: expiration, + maxDuration: maxDuration, + minInterestRate: minInterestRate, + collateralTokenAddress: address(collateralToken), + collateralTokenId: collateralTokenId, + maxPrincipalPerCollateralAmount: maxPrincipalPerCollateralAmount, + collateralTokenType: collateralTokenType, + lender: address(lender), + marketId: marketId, + principalTokenAddress: address(principalToken) + }); + + // uint256 c_id = lender._createCommitment(c, emptyArray); + + address[] memory _borrowerAddressList ; + IUniswapPricingLibrary.PoolRouteConfig[] + memory _poolRoutes = new IUniswapPricingLibrary.PoolRouteConfig[]( + 2 + ); + + bool zeroForOne = false; + uint32 twapInterval = 10; + + _poolRoutes[0] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPool), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + _poolRoutes[1] = IUniswapPricingLibrary.PoolRouteConfig({ + pool: address(mockUniswapPoolSecondary), + zeroForOne: zeroForOne, + twapInterval: twapInterval, + token0Decimals: 18, + token1Decimals: 18 + }); + + + vm.prank(address(lender)); + vm.expectRevert( "can only use pool routes with ERC20 collateral" ); + + uint256 _commitmentId = lenderCommitmentForwarder + .createCommitmentWithUniswap( + _commitment, + _borrowerAddressList, + _poolRoutes, + 10000 + ); + + } + + + + + function test_getEscrowCollateralType_erc20() public { + CollateralType cType = lenderCommitmentForwarder + ._getEscrowCollateralTypeSuper( + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC20 + ); + + assertEq( + uint16(cType), + uint16(CollateralType.ERC20), + "unexpected collateral type" + ); + } + + function test_getEscrowCollateralType_erc721() public { + CollateralType cType = lenderCommitmentForwarder + ._getEscrowCollateralTypeSuper( + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC721 + ); + + assertEq( + uint16(cType), + uint16(CollateralType.ERC721), + "unexpected collateral type" + ); + } + + function test_getEscrowCollateralType_erc1155() public { + CollateralType cType = lenderCommitmentForwarder + ._getEscrowCollateralTypeSuper( + ILenderCommitmentForwarder_U2.CommitmentCollateralType.ERC1155 + ); + + assertEq( + uint16(cType), + uint16(CollateralType.ERC1155), + "unexpected collateral type" + ); + } + + function test_getEscrowCollateralType_unknown() public { + vm.expectRevert("Unknown Collateral Type"); + CollateralType cType = lenderCommitmentForwarder + ._getEscrowCollateralTypeSuper( + ILenderCommitmentForwarder_U2.CommitmentCollateralType.NONE + ); + + ///assertEq(uint16(cType), uint16(CollateralType.NONE), "unexpected collateral type"); + } + + +} + +contract LenderCommitmentUser is User { + LenderCommitmentForwarder_G2 public immutable commitmentForwarder; + + constructor(address _tellerV2, address _commitmentForwarder) + User(_tellerV2) + { + commitmentForwarder = LenderCommitmentForwarder_G2( + _commitmentForwarder + ); + } + + function _createCommitment( + ILenderCommitmentForwarder.Commitment calldata _commitment, + address[] calldata borrowerAddressList + ) public returns (uint256) { + return + commitmentForwarder.createCommitment( + _commitment, + borrowerAddressList + ); + } + + function _acceptCommitment( + uint256 commitmentId, + uint256 principal, + uint256 collateralAmount, + uint256 collateralTokenId, + address collateralTokenAddress, + uint16 interestRate, + uint32 loanDuration + ) public returns (uint256) { + return + commitmentForwarder.acceptCommitment( + commitmentId, + principal, + collateralAmount, + collateralTokenId, + collateralTokenAddress, + interestRate, + loanDuration + ); + } + + function _deleteCommitment(uint256 _commitmentId) public { + commitmentForwarder.deleteCommitment(_commitmentId); + } +} + +//Move to a helper file ! +contract LenderCommitmentForwarderTest_TellerV2Mock is TellerV2Context { + constructor() TellerV2Context(address(0)) {} + + function __setMarketRegistry(address _marketRegistry) external { + marketRegistry = IMarketRegistry(_marketRegistry); + } + + function getSenderForMarket(uint256 _marketId) + external + view + returns (address) + { + return _msgSenderForMarket(_marketId); + } + + function getDataForMarket(uint256 _marketId) + external + view + returns (bytes calldata) + { + return _msgDataForMarket(_marketId); + } +} From 634ef29195e006eb480b4147dc46c9c397b6667b Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 3 Apr 2025 15:26:51 -0400 Subject: [PATCH 3/6] deploy script for lcfa v2 --- .../LenderCommitmentForwarderAlpha.sol | 6 +- .../LenderCommitmentForwarderV2.sol | 21 ++++ .../deploy_lcf_v2.ts | 60 +++++++++ .../25_upgrade_lcfa_pricing_library.ts | 114 ------------------ 4 files changed, 84 insertions(+), 117 deletions(-) create mode 100644 packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderV2.sol create mode 100644 packages/contracts/deploy/lender_commitment_forwarder/deploy_lcf_v2.ts delete mode 100644 packages/contracts/deploy/upgrades/25_upgrade_lcfa_pricing_library.ts diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol b/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol index 936eb06a4..61d33de97 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderAlpha.sol @@ -1,15 +1,15 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; -import "./LenderCommitmentForwarder_U2.sol"; +import "./LenderCommitmentForwarder_U1.sol"; -contract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U2 { +contract LenderCommitmentForwarderAlpha is LenderCommitmentForwarder_U1 { constructor( address _tellerV2, address _marketRegistry, address _uniswapV3Factory ) - LenderCommitmentForwarder_U2( + LenderCommitmentForwarder_U1( _tellerV2, _marketRegistry, _uniswapV3Factory diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderV2.sol b/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderV2.sol new file mode 100644 index 000000000..051c51411 --- /dev/null +++ b/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarderV2.sol @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: UNLICENSED +pragma solidity ^0.8.0; + +import "./LenderCommitmentForwarder_U2.sol"; + +contract LenderCommitmentForwarderV2 is LenderCommitmentForwarder_U2 { + constructor( + address _tellerV2, + address _marketRegistry, + address _uniswapV3Factory + ) + LenderCommitmentForwarder_U2( + _tellerV2, + _marketRegistry, + _uniswapV3Factory + ) + { + // we only want this on an proxy deployment so it only affects the impl + _disableInitializers(); + } +} diff --git a/packages/contracts/deploy/lender_commitment_forwarder/deploy_lcf_v2.ts b/packages/contracts/deploy/lender_commitment_forwarder/deploy_lcf_v2.ts new file mode 100644 index 000000000..35039434f --- /dev/null +++ b/packages/contracts/deploy/lender_commitment_forwarder/deploy_lcf_v2.ts @@ -0,0 +1,60 @@ +import { DeployFunction } from 'hardhat-deploy/dist/types' + +const deployFn: DeployFunction = async (hre) => { + const tellerV2 = await hre.contracts.get('TellerV2') + const marketRegistry = await hre.contracts.get('MarketRegistry') + + let uniswapFactoryAddress: string + switch (hre.network.name) { + case 'mainnet': + case 'goerli': + case 'arbitrum': + case 'optimism': + case 'polygon': + case 'localhost': + uniswapFactoryAddress = '0x1F98431c8aD98523631AE4a59f267346ea31F984' + break + case 'base': + uniswapFactoryAddress = '0x33128a8fC17869897dcE68Ed026d694621f6FDfD' + break + case 'sepolia': + uniswapFactoryAddress = '0x0227628f3F023bb0B980b67D528571c95c6DaC1c' + break + default: + throw new Error('No swap factory address found for this network') + } + + + const uniswapPricingLibraryV2 = await hre.contracts.get('UniswapPricingLibraryV2') + + + + + const lenderCommitmentForwarderAlpha = await hre.deployProxy( + 'LenderCommitmentForwarderV2', + { + unsafeAllow: ['constructor', 'state-variable-immutable'], + constructorArgs: [ + await tellerV2.getAddress(), + await marketRegistry.getAddress(), + uniswapFactoryAddress, + ], + libraries: { + + UniswapPricingLibraryV2: await uniswapPricingLibraryV2.getAddress(), + } + } + ) + + return true +} + +// tags and deployment +deployFn.id = 'lender-commitment-forwarder:alpha:deploy' +deployFn.tags = [ + 'lender-commitment-forwarder', + 'lender-commitment-forwarder:alpha', + 'lender-commitment-forwarder:alpha:deploy', +] +deployFn.dependencies = ['teller-v2:deploy', 'market-registry:deploy','teller-v2:uniswap-pricing-library-v2'] +export default deployFn diff --git a/packages/contracts/deploy/upgrades/25_upgrade_lcfa_pricing_library.ts b/packages/contracts/deploy/upgrades/25_upgrade_lcfa_pricing_library.ts deleted file mode 100644 index dcb24f93b..000000000 --- a/packages/contracts/deploy/upgrades/25_upgrade_lcfa_pricing_library.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { DeployFunction } from 'hardhat-deploy/dist/types' - -const deployFn: DeployFunction = async (hre) => { - hre.log('----------') - hre.log('') - hre.log('LenderCommitmentForwarderAlpha: Proposing upgrade...') - - const chainId = await hre.getChainId() - - let uniswapFactoryAddress: string - switch (hre.network.name) { - case 'mainnet': - case 'goerli': - case 'arbitrum': - case 'optimism': - case 'polygon': - case 'localhost': - uniswapFactoryAddress = '0x1F98431c8aD98523631AE4a59f267346ea31F984' - break - case 'base': - uniswapFactoryAddress = '0x33128a8fC17869897dcE68Ed026d694621f6FDfD' - break - case 'sepolia': - uniswapFactoryAddress = '0x0227628f3F023bb0B980b67D528571c95c6DaC1c' - break - default: - throw new Error('No swap factory address found for this network') - } - - const tellerV2 = await hre.contracts.get('TellerV2') - - const marketRegistry = await hre.contracts.get('MarketRegistry') - - const lenderCommitmentForwarderAlpha = await hre.contracts.get( - 'LenderCommitmentForwarderAlpha' - ) - - const tellerV2ProxyAddress = await tellerV2.getAddress() - const marketRegistryProxyAddress = await marketRegistry.getAddress() - const lcfAlphaProxyAddress = await lenderCommitmentForwarderAlpha.getAddress() - - const uniswapPricingLibraryV2 = await hre.deployments.get('uniswapPricingLibraryV2') - - - const LenderCommitmentForwarderAlphaImplementation = - await hre.ethers.getContractFactory('LenderCommitmentForwarderAlpha', { - - - libraries: { - uniswapPricingLibraryV2: uniswapPricingLibraryV2.address, - }, - - - }) - - - - await hre.upgrades.proposeBatchTimelock({ - title: 'LenderCommitmentForwarderAlpha: Upgrade Fix 1', - description: ` -# LenderCommitmentForwarderAlpha - -* Upgrade to fix maxPrincipal require statement. -`, - _steps: [ - { - proxy: lcfAlphaProxyAddress, - implFactory: LenderCommitmentForwarderAlphaImplementation, - - opts: { - unsafeAllow: ['constructor', 'state-variable-immutable'], - - constructorArgs: [ - tellerV2ProxyAddress, - marketRegistryProxyAddress, - uniswapFactoryAddress, - ], - }, - }, - ], - }) - - - hre.log('done.') - hre.log('') - hre.log('----------') - - return true -} - -// tags and deployment -deployFn.id = 'lender-commitment-forwarder:alpha:upgrade_max_principal' -deployFn.tags = [ - 'proposal', - 'upgrade', - 'lender-commitment-forwarder:alpha', - 'lender-commitment-forwarder:alpha:upgrade_max_principal', -] -deployFn.dependencies = ['lender-commitment-forwarder:alpha:deploy'] -deployFn.skip = async (hre) => { - return ( - !hre.network.live || - ![ - 'localhost', - 'polygon', - 'arbitrum', - 'base', - 'mainnet', - 'sepolia' - - ].includes(hre.network.name) - ) -} -export default deployFn From 498532a01bfc6579f2e1d820be3838627372141e Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 3 Apr 2025 15:36:17 -0400 Subject: [PATCH 4/6] prep for lcfaV2 deploy --- packages/contracts/.openzeppelin/mainnet.json | 684 ++++++++++++++++++ .../deploy_lcf_v2.ts | 8 +- .../uniswap_pricing_libraryV2.ts | 6 + .../mainnet/CollateralEscrowBeacon.json | 4 +- .../c4af209b4dcb1fbdc66baa1eb36588ed.json | 413 +++++++++++ 5 files changed, 1109 insertions(+), 6 deletions(-) create mode 100644 packages/contracts/deployments/mainnet/solcInputs/c4af209b4dcb1fbdc66baa1eb36588ed.json diff --git a/packages/contracts/.openzeppelin/mainnet.json b/packages/contracts/.openzeppelin/mainnet.json index 530e7c928..c7388437f 100644 --- a/packages/contracts/.openzeppelin/mainnet.json +++ b/packages/contracts/.openzeppelin/mainnet.json @@ -99,6 +99,16 @@ "address": "0x7848585b707F54CcF7044F8C82CF53F43100dc83", "txHash": "0x77123456f4eb954b2fe8c071fad7dbd8a5342902458f50aa50f61e9afd8e5eb8", "kind": "transparent" + }, + { + "address": "0x48EA70BCe76FE2F0c79B29Bf852a1DCF957982aa", + "txHash": "0x7e8f21528b3824eb26e6a6ac0310c2f8c6c1e2add4b9161dc4aec8b4c56f2f09", + "kind": "transparent" + }, + { + "address": "0x208289DD22D4cf59fb18A2CE073A128D5286bD2F", + "txHash": "0x2211b5b2c477b70208d4ff989c35e3125d5aaeda172982f3e2ffc535945ee536", + "kind": "transparent" } ], "impls": { @@ -8997,6 +9007,680 @@ "types": {}, "namespaces": {} } + }, + "9b740c2b4e19814db8909083e4ca64fadf98da46629a44ad77352c135152b8ca": { + "address": "0xC764a44Faa62dB04310e0c8eA8d56FDC411e3e31", + "txHash": "0x73b4ceb16b58ea4583b1a111ae458344cba70a78a3404c7618dfc82fa0458ce2", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "userExtensions", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_address,t_mapping(t_address,t_bool))", + "contract": "ExtensionsContextUpgradeable", + "src": "contracts/LenderCommitmentForwarder/extensions/ExtensionsContextUpgradeable.sol:12" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)49_storage", + "contract": "ExtensionsContextUpgradeable", + "src": "contracts/LenderCommitmentForwarder/extensions/ExtensionsContextUpgradeable.sol:61" + }, + { + "label": "_initialized", + "offset": 0, + "slot": "50", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "50", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "51", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "__gap", + "offset": 0, + "slot": "101", + "type": "t_array(t_uint256)50_storage", + "contract": "TellerV2MarketForwarder_G2", + "src": "contracts/TellerV2MarketForwarder_G2.sol:149" + }, + { + "label": "commitments", + "offset": 0, + "slot": "151", + "type": "t_mapping(t_uint256,t_struct(Commitment)19680_storage)", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:58" + }, + { + "label": "commitmentCount", + "offset": 0, + "slot": "152", + "type": "t_uint256", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:60" + }, + { + "label": "commitmentBorrowersList", + "offset": 0, + "slot": "153", + "type": "t_mapping(t_uint256,t_struct(AddressSet)2837_storage)", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:63" + }, + { + "label": "commitmentPrincipalAccepted", + "offset": 0, + "slot": "154", + "type": "t_mapping(t_uint256,t_uint256)", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:67" + }, + { + "label": "commitmentUniswapPoolRoutes", + "offset": 0, + "slot": "155", + "type": "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)20596_storage)dyn_storage)", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:69" + }, + { + "label": "commitmentPoolOracleLtvRatio", + "offset": 0, + "slot": "156", + "type": "t_mapping(t_uint256,t_uint16)", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:71" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "numberOfBytes": "32" + }, + "t_array(t_struct(PoolRouteConfig)20596_storage)dyn_storage": { + "label": "struct IUniswapPricingLibrary.PoolRouteConfig[]", + "numberOfBytes": "32" + }, + "t_array(t_uint256)49_storage": { + "label": "uint256[49]", + "numberOfBytes": "1568" + }, + "t_array(t_uint256)50_storage": { + "label": "uint256[50]", + "numberOfBytes": "1600" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_enum(CommitmentCollateralType)19656": { + "label": "enum ILenderCommitmentForwarder_U2.CommitmentCollateralType", + "members": [ + "NONE", + "ERC20", + "ERC721", + "ERC1155", + "ERC721_ANY_ID", + "ERC1155_ANY_ID", + "ERC721_MERKLE_PROOF", + "ERC1155_MERKLE_PROOF" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_bool)": { + "label": "mapping(address => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_address,t_bool))": { + "label": "mapping(address => mapping(address => bool))", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_uint256)": { + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)20596_storage)dyn_storage)": { + "label": "mapping(uint256 => struct IUniswapPricingLibrary.PoolRouteConfig[])", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(AddressSet)2837_storage)": { + "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(Commitment)19680_storage)": { + "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U2.Commitment)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint16)": { + "label": "mapping(uint256 => uint16)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint256)": { + "label": "mapping(uint256 => uint256)", + "numberOfBytes": "32" + }, + "t_struct(AddressSet)2837_storage": { + "label": "struct EnumerableSetUpgradeable.AddressSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)2522_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Commitment)19680_storage": { + "label": "struct ILenderCommitmentForwarder_U2.Commitment", + "members": [ + { + "label": "maxPrincipal", + "type": "t_uint256", + "offset": 0, + "slot": "0" + }, + { + "label": "expiration", + "type": "t_uint32", + "offset": 0, + "slot": "1" + }, + { + "label": "maxDuration", + "type": "t_uint32", + "offset": 4, + "slot": "1" + }, + { + "label": "minInterestRate", + "type": "t_uint16", + "offset": 8, + "slot": "1" + }, + { + "label": "collateralTokenAddress", + "type": "t_address", + "offset": 10, + "slot": "1" + }, + { + "label": "collateralTokenId", + "type": "t_uint256", + "offset": 0, + "slot": "2" + }, + { + "label": "maxPrincipalPerCollateralAmount", + "type": "t_uint256", + "offset": 0, + "slot": "3" + }, + { + "label": "collateralTokenType", + "type": "t_enum(CommitmentCollateralType)19656", + "offset": 0, + "slot": "4" + }, + { + "label": "lender", + "type": "t_address", + "offset": 1, + "slot": "4" + }, + { + "label": "marketId", + "type": "t_uint256", + "offset": 0, + "slot": "5" + }, + { + "label": "principalTokenAddress", + "type": "t_address", + "offset": 0, + "slot": "6" + } + ], + "numberOfBytes": "224" + }, + "t_struct(PoolRouteConfig)20596_storage": { + "label": "struct IUniswapPricingLibrary.PoolRouteConfig", + "members": [ + { + "label": "pool", + "type": "t_address", + "offset": 0, + "slot": "0" + }, + { + "label": "zeroForOne", + "type": "t_bool", + "offset": 20, + "slot": "0" + }, + { + "label": "twapInterval", + "type": "t_uint32", + "offset": 21, + "slot": "0" + }, + { + "label": "token0Decimals", + "type": "t_uint256", + "offset": 0, + "slot": "1" + }, + { + "label": "token1Decimals", + "type": "t_uint256", + "offset": 0, + "slot": "2" + } + ], + "numberOfBytes": "96" + }, + "t_struct(Set)2522_storage": { + "label": "struct EnumerableSetUpgradeable.Set", + "members": [ + { + "label": "_values", + "type": "t_array(t_bytes32)dyn_storage", + "offset": 0, + "slot": "0" + }, + { + "label": "_indexes", + "type": "t_mapping(t_bytes32,t_uint256)", + "offset": 0, + "slot": "1" + } + ], + "numberOfBytes": "64" + }, + "t_uint16": { + "label": "uint16", + "numberOfBytes": "2" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint32": { + "label": "uint32", + "numberOfBytes": "4" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } + }, + "20811f1dfbba31cd2d615a2f305ca5e2792788d8fba22cdb575112a2652906ea": { + "address": "0x838F8e08C723CA4323cacD07D57777B27eAB3bD4", + "txHash": "0x4519c1f4d8b9ce63d0653eb941e7a6a5a4785c150528eb57d8ab62c199b6cbdc", + "layout": { + "solcVersion": "0.8.11", + "storage": [ + { + "label": "userExtensions", + "offset": 0, + "slot": "0", + "type": "t_mapping(t_address,t_mapping(t_address,t_bool))", + "contract": "ExtensionsContextUpgradeable", + "src": "contracts/LenderCommitmentForwarder/extensions/ExtensionsContextUpgradeable.sol:12" + }, + { + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)49_storage", + "contract": "ExtensionsContextUpgradeable", + "src": "contracts/LenderCommitmentForwarder/extensions/ExtensionsContextUpgradeable.sol:61" + }, + { + "label": "_initialized", + "offset": 0, + "slot": "50", + "type": "t_uint8", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", + "retypedFrom": "bool" + }, + { + "label": "_initializing", + "offset": 1, + "slot": "50", + "type": "t_bool", + "contract": "Initializable", + "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" + }, + { + "label": "__gap", + "offset": 0, + "slot": "51", + "type": "t_array(t_uint256)50_storage", + "contract": "ContextUpgradeable", + "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" + }, + { + "label": "__gap", + "offset": 0, + "slot": "101", + "type": "t_array(t_uint256)50_storage", + "contract": "TellerV2MarketForwarder_G2", + "src": "contracts/TellerV2MarketForwarder_G2.sol:149" + }, + { + "label": "commitments", + "offset": 0, + "slot": "151", + "type": "t_mapping(t_uint256,t_struct(Commitment)19680_storage)", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:58" + }, + { + "label": "commitmentCount", + "offset": 0, + "slot": "152", + "type": "t_uint256", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:60" + }, + { + "label": "commitmentBorrowersList", + "offset": 0, + "slot": "153", + "type": "t_mapping(t_uint256,t_struct(AddressSet)2837_storage)", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:63" + }, + { + "label": "commitmentPrincipalAccepted", + "offset": 0, + "slot": "154", + "type": "t_mapping(t_uint256,t_uint256)", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:67" + }, + { + "label": "commitmentUniswapPoolRoutes", + "offset": 0, + "slot": "155", + "type": "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)20596_storage)dyn_storage)", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:69" + }, + { + "label": "commitmentPoolOracleLtvRatio", + "offset": 0, + "slot": "156", + "type": "t_mapping(t_uint256,t_uint16)", + "contract": "LenderCommitmentForwarder_U2", + "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:71" + } + ], + "types": { + "t_address": { + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_bytes32)dyn_storage": { + "label": "bytes32[]", + "numberOfBytes": "32" + }, + "t_array(t_struct(PoolRouteConfig)20596_storage)dyn_storage": { + "label": "struct IUniswapPricingLibrary.PoolRouteConfig[]", + "numberOfBytes": "32" + }, + "t_array(t_uint256)49_storage": { + "label": "uint256[49]", + "numberOfBytes": "1568" + }, + "t_array(t_uint256)50_storage": { + "label": "uint256[50]", + "numberOfBytes": "1600" + }, + "t_bool": { + "label": "bool", + "numberOfBytes": "1" + }, + "t_bytes32": { + "label": "bytes32", + "numberOfBytes": "32" + }, + "t_enum(CommitmentCollateralType)19656": { + "label": "enum ILenderCommitmentForwarder_U2.CommitmentCollateralType", + "members": [ + "NONE", + "ERC20", + "ERC721", + "ERC1155", + "ERC721_ANY_ID", + "ERC1155_ANY_ID", + "ERC721_MERKLE_PROOF", + "ERC1155_MERKLE_PROOF" + ], + "numberOfBytes": "1" + }, + "t_mapping(t_address,t_bool)": { + "label": "mapping(address => bool)", + "numberOfBytes": "32" + }, + "t_mapping(t_address,t_mapping(t_address,t_bool))": { + "label": "mapping(address => mapping(address => bool))", + "numberOfBytes": "32" + }, + "t_mapping(t_bytes32,t_uint256)": { + "label": "mapping(bytes32 => uint256)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)20596_storage)dyn_storage)": { + "label": "mapping(uint256 => struct IUniswapPricingLibrary.PoolRouteConfig[])", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(AddressSet)2837_storage)": { + "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_struct(Commitment)19680_storage)": { + "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U2.Commitment)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint16)": { + "label": "mapping(uint256 => uint16)", + "numberOfBytes": "32" + }, + "t_mapping(t_uint256,t_uint256)": { + "label": "mapping(uint256 => uint256)", + "numberOfBytes": "32" + }, + "t_struct(AddressSet)2837_storage": { + "label": "struct EnumerableSetUpgradeable.AddressSet", + "members": [ + { + "label": "_inner", + "type": "t_struct(Set)2522_storage", + "offset": 0, + "slot": "0" + } + ], + "numberOfBytes": "64" + }, + "t_struct(Commitment)19680_storage": { + "label": "struct ILenderCommitmentForwarder_U2.Commitment", + "members": [ + { + "label": "maxPrincipal", + "type": "t_uint256", + "offset": 0, + "slot": "0" + }, + { + "label": "expiration", + "type": "t_uint32", + "offset": 0, + "slot": "1" + }, + { + "label": "maxDuration", + "type": "t_uint32", + "offset": 4, + "slot": "1" + }, + { + "label": "minInterestRate", + "type": "t_uint16", + "offset": 8, + "slot": "1" + }, + { + "label": "collateralTokenAddress", + "type": "t_address", + "offset": 10, + "slot": "1" + }, + { + "label": "collateralTokenId", + "type": "t_uint256", + "offset": 0, + "slot": "2" + }, + { + "label": "maxPrincipalPerCollateralAmount", + "type": "t_uint256", + "offset": 0, + "slot": "3" + }, + { + "label": "collateralTokenType", + "type": "t_enum(CommitmentCollateralType)19656", + "offset": 0, + "slot": "4" + }, + { + "label": "lender", + "type": "t_address", + "offset": 1, + "slot": "4" + }, + { + "label": "marketId", + "type": "t_uint256", + "offset": 0, + "slot": "5" + }, + { + "label": "principalTokenAddress", + "type": "t_address", + "offset": 0, + "slot": "6" + } + ], + "numberOfBytes": "224" + }, + "t_struct(PoolRouteConfig)20596_storage": { + "label": "struct IUniswapPricingLibrary.PoolRouteConfig", + "members": [ + { + "label": "pool", + "type": "t_address", + "offset": 0, + "slot": "0" + }, + { + "label": "zeroForOne", + "type": "t_bool", + "offset": 20, + "slot": "0" + }, + { + "label": "twapInterval", + "type": "t_uint32", + "offset": 21, + "slot": "0" + }, + { + "label": "token0Decimals", + "type": "t_uint256", + "offset": 0, + "slot": "1" + }, + { + "label": "token1Decimals", + "type": "t_uint256", + "offset": 0, + "slot": "2" + } + ], + "numberOfBytes": "96" + }, + "t_struct(Set)2522_storage": { + "label": "struct EnumerableSetUpgradeable.Set", + "members": [ + { + "label": "_values", + "type": "t_array(t_bytes32)dyn_storage", + "offset": 0, + "slot": "0" + }, + { + "label": "_indexes", + "type": "t_mapping(t_bytes32,t_uint256)", + "offset": 0, + "slot": "1" + } + ], + "numberOfBytes": "64" + }, + "t_uint16": { + "label": "uint16", + "numberOfBytes": "2" + }, + "t_uint256": { + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint32": { + "label": "uint32", + "numberOfBytes": "4" + }, + "t_uint8": { + "label": "uint8", + "numberOfBytes": "1" + } + }, + "namespaces": {} + } } } } diff --git a/packages/contracts/deploy/lender_commitment_forwarder/deploy_lcf_v2.ts b/packages/contracts/deploy/lender_commitment_forwarder/deploy_lcf_v2.ts index 35039434f..d2673118f 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/deploy_lcf_v2.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/deploy_lcf_v2.ts @@ -33,7 +33,7 @@ const deployFn: DeployFunction = async (hre) => { const lenderCommitmentForwarderAlpha = await hre.deployProxy( 'LenderCommitmentForwarderV2', { - unsafeAllow: ['constructor', 'state-variable-immutable'], + unsafeAllow: ['constructor', 'state-variable-immutable','external-library-linking'], constructorArgs: [ await tellerV2.getAddress(), await marketRegistry.getAddress(), @@ -50,11 +50,11 @@ const deployFn: DeployFunction = async (hre) => { } // tags and deployment -deployFn.id = 'lender-commitment-forwarder:alpha:deploy' +deployFn.id = 'lender-commitment-forwarder:v2:deploy' deployFn.tags = [ 'lender-commitment-forwarder', - 'lender-commitment-forwarder:alpha', - 'lender-commitment-forwarder:alpha:deploy', + 'lender-commitment-forwarder:v2', + 'lender-commitment-forwarder:v2:deploy', ] deployFn.dependencies = ['teller-v2:deploy', 'market-registry:deploy','teller-v2:uniswap-pricing-library-v2'] export default deployFn diff --git a/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts b/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts index f39387a25..5136c2013 100644 --- a/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts +++ b/packages/contracts/deploy/lender_commitment_forwarder/uniswap_pricing_libraryV2.ts @@ -7,6 +7,12 @@ const deployFn: DeployFunction = async (hre) => { }) } + + + + hre.log('Deploying uniswapPricingLibraryV2...') + + // tags and deployment deployFn.id = 'teller-v2:uniswap-pricing-library-v2' deployFn.tags = ['teller-v2', 'teller-v2:uniswap-pricing-library-v2'] diff --git a/packages/contracts/deployments/mainnet/CollateralEscrowBeacon.json b/packages/contracts/deployments/mainnet/CollateralEscrowBeacon.json index 4db50bbc1..ca80dc921 100644 --- a/packages/contracts/deployments/mainnet/CollateralEscrowBeacon.json +++ b/packages/contracts/deployments/mainnet/CollateralEscrowBeacon.json @@ -375,6 +375,6 @@ "status": 1, "byzantium": true }, - "numDeployments": 11, - "implementation": "0x86D540Ca6de284c18BeED0F6f154499CF9b61322" + "numDeployments": 12, + "implementation": "0x0410535A1C3c59Ce477644f21662b5A96b4bA085" } \ No newline at end of file diff --git a/packages/contracts/deployments/mainnet/solcInputs/c4af209b4dcb1fbdc66baa1eb36588ed.json b/packages/contracts/deployments/mainnet/solcInputs/c4af209b4dcb1fbdc66baa1eb36588ed.json new file mode 100644 index 000000000..14d369a27 --- /dev/null +++ b/packages/contracts/deployments/mainnet/solcInputs/c4af209b4dcb1fbdc66baa1eb36588ed.json @@ -0,0 +1,413 @@ +{ + "language": "Solidity", + "sources": { + "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../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 Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/metatx/ERC2771ContextUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.9;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n */\nabstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address private immutable _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder) public view virtual returns (bool) {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender() internal view virtual override returns (address sender) {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n /// @solidity memory-safe-assembly\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData() internal view virtual override returns (bytes calldata) {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\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/proxy/utils/Initializable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.1) (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.\n *\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\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 * WARNING: setting the version to 255 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized < type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n\n /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint8) {\n return _initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _initializing;\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../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 Modifier to make a function callable only when the contract is not paused.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n modifier whenNotPaused() {\n _requireNotPaused();\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n modifier whenPaused() {\n _requirePaused();\n _;\n }\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view virtual returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Throws if the contract is paused.\n */\n function _requireNotPaused() internal view virtual {\n require(!paused(), \"Pausable: paused\");\n }\n\n /**\n * @dev Throws if the contract is not paused.\n */\n function _requirePaused() internal view virtual {\n require(paused(), \"Pausable: not paused\");\n }\n\n /**\n * @dev Triggers stopped state.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" + }, + "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (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 _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n // On the first call to nonReentrant, _status will be _NOT_ENTERED\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n }\n\n function _nonReentrantAfter() private {\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/ERC20/extensions/IERC20MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\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/token/ERC721/IERC721Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.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 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: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n * understand this adds an external call which potentially creates a reentrancy vulnerability.\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/utils/AddressUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.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 functionCallWithValue(target, data, 0, \"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 (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, 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 (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or 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 _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\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" + }, + "@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/cryptography/MerkleProofUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/MerkleProof.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev These functions deal with verification of Merkle Tree proofs.\n *\n * The tree and the proofs can be generated using our\n * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].\n * You will find a quickstart guide in the readme.\n *\n * WARNING: You should avoid using leaf values that are 64 bytes long prior to\n * hashing, or use a hash function other than keccak256 for hashing leaves.\n * This is because the concatenation of a sorted pair of internal nodes in\n * the merkle tree could be reinterpreted as a leaf value.\n * OpenZeppelin's JavaScript library generates merkle trees that are safe\n * against this attack out of the box.\n */\nlibrary MerkleProofUpgradeable {\n /**\n * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree\n * defined by `root`. For this, a `proof` must be provided, containing\n * sibling hashes on the branch from the leaf to the root of the tree. Each\n * pair of leaves and each pair of pre-images are assumed to be sorted.\n */\n function verify(\n bytes32[] memory proof,\n bytes32 root,\n bytes32 leaf\n ) internal pure returns (bool) {\n return processProof(proof, leaf) == root;\n }\n\n /**\n * @dev Calldata version of {verify}\n *\n * _Available since v4.7._\n */\n function verifyCalldata(\n bytes32[] calldata proof,\n bytes32 root,\n bytes32 leaf\n ) internal pure returns (bool) {\n return processProofCalldata(proof, leaf) == root;\n }\n\n /**\n * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up\n * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt\n * hash matches the root of the tree. When processing the proof, the pairs\n * of leafs & pre-images are assumed to be sorted.\n *\n * _Available since v4.4._\n */\n function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {\n bytes32 computedHash = leaf;\n for (uint256 i = 0; i < proof.length; i++) {\n computedHash = _hashPair(computedHash, proof[i]);\n }\n return computedHash;\n }\n\n /**\n * @dev Calldata version of {processProof}\n *\n * _Available since v4.7._\n */\n function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {\n bytes32 computedHash = leaf;\n for (uint256 i = 0; i < proof.length; i++) {\n computedHash = _hashPair(computedHash, proof[i]);\n }\n return computedHash;\n }\n\n /**\n * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by\n * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.\n *\n * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.\n *\n * _Available since v4.7._\n */\n function multiProofVerify(\n bytes32[] memory proof,\n bool[] memory proofFlags,\n bytes32 root,\n bytes32[] memory leaves\n ) internal pure returns (bool) {\n return processMultiProof(proof, proofFlags, leaves) == root;\n }\n\n /**\n * @dev Calldata version of {multiProofVerify}\n *\n * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.\n *\n * _Available since v4.7._\n */\n function multiProofVerifyCalldata(\n bytes32[] calldata proof,\n bool[] calldata proofFlags,\n bytes32 root,\n bytes32[] memory leaves\n ) internal pure returns (bool) {\n return processMultiProofCalldata(proof, proofFlags, leaves) == root;\n }\n\n /**\n * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction\n * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another\n * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false\n * respectively.\n *\n * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree\n * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the\n * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).\n *\n * _Available since v4.7._\n */\n function processMultiProof(\n bytes32[] memory proof,\n bool[] memory proofFlags,\n bytes32[] memory leaves\n ) internal pure returns (bytes32 merkleRoot) {\n // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by\n // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\n // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\n // the merkle tree.\n uint256 leavesLen = leaves.length;\n uint256 totalHashes = proofFlags.length;\n\n // Check proof validity.\n require(leavesLen + proof.length - 1 == totalHashes, \"MerkleProof: invalid multiproof\");\n\n // The xxxPos values are \"pointers\" to the next value to consume in each array. All accesses are done using\n // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \"pop\".\n bytes32[] memory hashes = new bytes32[](totalHashes);\n uint256 leafPos = 0;\n uint256 hashPos = 0;\n uint256 proofPos = 0;\n // At each step, we compute the next hash using two values:\n // - a value from the \"main queue\". If not all leaves have been consumed, we get the next leaf, otherwise we\n // get the next hash.\n // - depending on the flag, either another value for the \"main queue\" (merging branches) or an element from the\n // `proof` array.\n for (uint256 i = 0; i < totalHashes; i++) {\n bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\n bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];\n hashes[i] = _hashPair(a, b);\n }\n\n if (totalHashes > 0) {\n return hashes[totalHashes - 1];\n } else if (leavesLen > 0) {\n return leaves[0];\n } else {\n return proof[0];\n }\n }\n\n /**\n * @dev Calldata version of {processMultiProof}.\n *\n * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.\n *\n * _Available since v4.7._\n */\n function processMultiProofCalldata(\n bytes32[] calldata proof,\n bool[] calldata proofFlags,\n bytes32[] memory leaves\n ) internal pure returns (bytes32 merkleRoot) {\n // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by\n // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\n // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\n // the merkle tree.\n uint256 leavesLen = leaves.length;\n uint256 totalHashes = proofFlags.length;\n\n // Check proof validity.\n require(leavesLen + proof.length - 1 == totalHashes, \"MerkleProof: invalid multiproof\");\n\n // The xxxPos values are \"pointers\" to the next value to consume in each array. All accesses are done using\n // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \"pop\".\n bytes32[] memory hashes = new bytes32[](totalHashes);\n uint256 leafPos = 0;\n uint256 hashPos = 0;\n uint256 proofPos = 0;\n // At each step, we compute the next hash using two values:\n // - a value from the \"main queue\". If not all leaves have been consumed, we get the next leaf, otherwise we\n // get the next hash.\n // - depending on the flag, either another value for the \"main queue\" (merging branches) or an element from the\n // `proof` array.\n for (uint256 i = 0; i < totalHashes; i++) {\n bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\n bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];\n hashes[i] = _hashPair(a, b);\n }\n\n if (totalHashes > 0) {\n return hashes[totalHashes - 1];\n } else if (leavesLen > 0) {\n return leaves[0];\n } else {\n return proof[0];\n }\n }\n\n function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {\n return a < b ? _efficientHash(a, b) : _efficientHash(b, a);\n }\n\n function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x00, a)\n mstore(0x20, b)\n value := keccak256(0x00, 0x40)\n }\n }\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/utils/math/MathUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.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 MathUpgradeable {\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 //\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)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\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 unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n" + }, + "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSetUpgradeable {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping(bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) {\n // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n if (lastIndex != toDeleteIndex) {\n bytes32 lastValue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastValue;\n // Update the index for the moved value\n set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n }\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n return set._values[index];\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function _values(Set storage set) private view returns (bytes32[] memory) {\n return set._values;\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n bytes32[] memory store = _values(set._inner);\n bytes32[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(AddressSet storage set) internal view returns (address[] memory) {\n bytes32[] memory store = _values(set._inner);\n address[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(UintSet storage set) internal view returns (uint256[] memory) {\n bytes32[] memory store = _values(set._inner);\n uint256[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n}\n" + }, + "@openzeppelin/contracts/access/Ownable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/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 */\nabstract contract Ownable is Context {\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 constructor() {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n" + }, + "@openzeppelin/contracts/governance/utils/IVotes.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)\npragma solidity ^0.8.0;\n\n/**\n * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.\n *\n * _Available since v4.5._\n */\ninterface IVotes {\n /**\n * @dev Emitted when an account changes their delegate.\n */\n event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\n\n /**\n * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.\n */\n event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);\n\n /**\n * @dev Returns the current amount of votes that `account` has.\n */\n function getVotes(address account) external view returns (uint256);\n\n /**\n * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).\n */\n function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);\n\n /**\n * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).\n *\n * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.\n * Votes that have not been delegated are still part of total supply, even though they would not participate in a\n * vote.\n */\n function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);\n\n /**\n * @dev Returns the delegate that `account` has chosen.\n */\n function delegates(address account) external view returns (address);\n\n /**\n * @dev Delegates votes from the sender to `delegatee`.\n */\n function delegate(address delegatee) external;\n\n /**\n * @dev Delegates votes from signer to `delegatee`.\n */\n function delegateBySig(\n address delegatee,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/ERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n // decrementing then incrementing.\n _balances[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n unchecked {\n // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n _balances[account] += amount;\n }\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n // Overflow not possible: amount <= accountBalance <= totalSupply.\n _totalSupply -= amount;\n }\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens 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 amount\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, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/extensions/draft-ERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./draft-IERC20Permit.sol\";\nimport \"../ERC20.sol\";\nimport \"../../../utils/cryptography/ECDSA.sol\";\nimport \"../../../utils/cryptography/EIP712.sol\";\nimport \"../../../utils/Counters.sol\";\n\n/**\n * @dev Implementation 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 *\n * _Available since v3.4._\n */\nabstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {\n using Counters for Counters.Counter;\n\n mapping(address => Counters.Counter) private _nonces;\n\n // solhint-disable-next-line var-name-mixedcase\n bytes32 private constant _PERMIT_TYPEHASH =\n keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n /**\n * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.\n * However, to ensure consistency with the upgradeable transpiler, we will continue\n * to reserve a slot.\n * @custom:oz-renamed-from _PERMIT_TYPEHASH\n */\n // solhint-disable-next-line var-name-mixedcase\n bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;\n\n /**\n * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `\"1\"`.\n *\n * It's a good idea to use the same `name` that is defined as the ERC20 token name.\n */\n constructor(string memory name) EIP712(name, \"1\") {}\n\n /**\n * @dev See {IERC20Permit-permit}.\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 ) public virtual override {\n require(block.timestamp <= deadline, \"ERC20Permit: expired deadline\");\n\n bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));\n\n bytes32 hash = _hashTypedDataV4(structHash);\n\n address signer = ECDSA.recover(hash, v, r, s);\n require(signer == owner, \"ERC20Permit: invalid signature\");\n\n _approve(owner, spender, value);\n }\n\n /**\n * @dev See {IERC20Permit-nonces}.\n */\n function nonces(address owner) public view virtual override returns (uint256) {\n return _nonces[owner].current();\n }\n\n /**\n * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view override returns (bytes32) {\n return _domainSeparatorV4();\n }\n\n /**\n * @dev \"Consume a nonce\": return the current value and increment.\n *\n * _Available since v4.1._\n */\n function _useNonce(address owner) internal virtual returns (uint256 current) {\n Counters.Counter storage nonce = _nonces[owner];\n current = nonce.current();\n nonce.increment();\n }\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/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.0;\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}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.1) (token/ERC20/extensions/ERC20Votes.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./draft-ERC20Permit.sol\";\nimport \"../../../utils/math/Math.sol\";\nimport \"../../../governance/utils/IVotes.sol\";\nimport \"../../../utils/math/SafeCast.sol\";\nimport \"../../../utils/cryptography/ECDSA.sol\";\n\n/**\n * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,\n * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.\n *\n * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.\n *\n * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either\n * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting\n * power can be queried through the public accessors {getVotes} and {getPastVotes}.\n *\n * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it\n * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.\n *\n * _Available since v4.2._\n */\nabstract contract ERC20Votes is IVotes, ERC20Permit {\n struct Checkpoint {\n uint32 fromBlock;\n uint224 votes;\n }\n\n bytes32 private constant _DELEGATION_TYPEHASH =\n keccak256(\"Delegation(address delegatee,uint256 nonce,uint256 expiry)\");\n\n mapping(address => address) private _delegates;\n mapping(address => Checkpoint[]) private _checkpoints;\n Checkpoint[] private _totalSupplyCheckpoints;\n\n /**\n * @dev Get the `pos`-th checkpoint for `account`.\n */\n function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {\n return _checkpoints[account][pos];\n }\n\n /**\n * @dev Get number of checkpoints for `account`.\n */\n function numCheckpoints(address account) public view virtual returns (uint32) {\n return SafeCast.toUint32(_checkpoints[account].length);\n }\n\n /**\n * @dev Get the address `account` is currently delegating to.\n */\n function delegates(address account) public view virtual override returns (address) {\n return _delegates[account];\n }\n\n /**\n * @dev Gets the current votes balance for `account`\n */\n function getVotes(address account) public view virtual override returns (uint256) {\n uint256 pos = _checkpoints[account].length;\n return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;\n }\n\n /**\n * @dev Retrieve the number of votes for `account` at the end of `blockNumber`.\n *\n * Requirements:\n *\n * - `blockNumber` must have been already mined\n */\n function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {\n require(blockNumber < block.number, \"ERC20Votes: block not yet mined\");\n return _checkpointsLookup(_checkpoints[account], blockNumber);\n }\n\n /**\n * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.\n * It is but NOT the sum of all the delegated votes!\n *\n * Requirements:\n *\n * - `blockNumber` must have been already mined\n */\n function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {\n require(blockNumber < block.number, \"ERC20Votes: block not yet mined\");\n return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);\n }\n\n /**\n * @dev Lookup a value in a list of (sorted) checkpoints.\n */\n function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {\n // We run a binary search to look for the earliest checkpoint taken after `blockNumber`.\n //\n // Initially we check if the block is recent to narrow the search range.\n // During the loop, the index of the wanted checkpoint remains in the range [low-1, high).\n // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.\n // - If the middle checkpoint is after `blockNumber`, we look in [low, mid)\n // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)\n // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not\n // out of bounds (in which case we're looking too far in the past and the result is 0).\n // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is\n // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out\n // the same.\n uint256 length = ckpts.length;\n\n uint256 low = 0;\n uint256 high = length;\n\n if (length > 5) {\n uint256 mid = length - Math.sqrt(length);\n if (_unsafeAccess(ckpts, mid).fromBlock > blockNumber) {\n high = mid;\n } else {\n low = mid + 1;\n }\n }\n\n while (low < high) {\n uint256 mid = Math.average(low, high);\n if (_unsafeAccess(ckpts, mid).fromBlock > blockNumber) {\n high = mid;\n } else {\n low = mid + 1;\n }\n }\n\n return high == 0 ? 0 : _unsafeAccess(ckpts, high - 1).votes;\n }\n\n /**\n * @dev Delegate votes from the sender to `delegatee`.\n */\n function delegate(address delegatee) public virtual override {\n _delegate(_msgSender(), delegatee);\n }\n\n /**\n * @dev Delegates votes from signer to `delegatee`\n */\n function delegateBySig(\n address delegatee,\n uint256 nonce,\n uint256 expiry,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public virtual override {\n require(block.timestamp <= expiry, \"ERC20Votes: signature expired\");\n address signer = ECDSA.recover(\n _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),\n v,\n r,\n s\n );\n require(nonce == _useNonce(signer), \"ERC20Votes: invalid nonce\");\n _delegate(signer, delegatee);\n }\n\n /**\n * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).\n */\n function _maxSupply() internal view virtual returns (uint224) {\n return type(uint224).max;\n }\n\n /**\n * @dev Snapshots the totalSupply after it has been increased.\n */\n function _mint(address account, uint256 amount) internal virtual override {\n super._mint(account, amount);\n require(totalSupply() <= _maxSupply(), \"ERC20Votes: total supply risks overflowing votes\");\n\n _writeCheckpoint(_totalSupplyCheckpoints, _add, amount);\n }\n\n /**\n * @dev Snapshots the totalSupply after it has been decreased.\n */\n function _burn(address account, uint256 amount) internal virtual override {\n super._burn(account, amount);\n\n _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);\n }\n\n /**\n * @dev Move voting power when tokens are transferred.\n *\n * Emits a {IVotes-DelegateVotesChanged} event.\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override {\n super._afterTokenTransfer(from, to, amount);\n\n _moveVotingPower(delegates(from), delegates(to), amount);\n }\n\n /**\n * @dev Change delegation for `delegator` to `delegatee`.\n *\n * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}.\n */\n function _delegate(address delegator, address delegatee) internal virtual {\n address currentDelegate = delegates(delegator);\n uint256 delegatorBalance = balanceOf(delegator);\n _delegates[delegator] = delegatee;\n\n emit DelegateChanged(delegator, currentDelegate, delegatee);\n\n _moveVotingPower(currentDelegate, delegatee, delegatorBalance);\n }\n\n function _moveVotingPower(\n address src,\n address dst,\n uint256 amount\n ) private {\n if (src != dst && amount > 0) {\n if (src != address(0)) {\n (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);\n emit DelegateVotesChanged(src, oldWeight, newWeight);\n }\n\n if (dst != address(0)) {\n (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);\n emit DelegateVotesChanged(dst, oldWeight, newWeight);\n }\n }\n }\n\n function _writeCheckpoint(\n Checkpoint[] storage ckpts,\n function(uint256, uint256) view returns (uint256) op,\n uint256 delta\n ) private returns (uint256 oldWeight, uint256 newWeight) {\n uint256 pos = ckpts.length;\n\n Checkpoint memory oldCkpt = pos == 0 ? Checkpoint(0, 0) : _unsafeAccess(ckpts, pos - 1);\n\n oldWeight = oldCkpt.votes;\n newWeight = op(oldWeight, delta);\n\n if (pos > 0 && oldCkpt.fromBlock == block.number) {\n _unsafeAccess(ckpts, pos - 1).votes = SafeCast.toUint224(newWeight);\n } else {\n ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)}));\n }\n }\n\n function _add(uint256 a, uint256 b) private pure returns (uint256) {\n return a + b;\n }\n\n function _subtract(uint256 a, uint256 b) private pure returns (uint256) {\n return a - b;\n }\n\n /**\n * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.\n */\n function _unsafeAccess(Checkpoint[] storage ckpts, uint256 pos) private pure returns (Checkpoint storage result) {\n assembly {\n mstore(0, ckpts.slot)\n result.slot := add(keccak256(0, 0x20), pos)\n }\n }\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/IERC20.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 IERC20 {\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/token/ERC20/utils/SafeERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/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}\n" + }, + "@openzeppelin/contracts/utils/Address.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\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 functionCallWithValue(target, data, 0, \"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 (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, 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 (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, 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 (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or 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 _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\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" + }, + "@openzeppelin/contracts/utils/Context.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\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 Context {\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" + }, + "@openzeppelin/contracts/utils/Counters.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title Counters\n * @author Matt Condon (@shrugs)\n * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number\n * of elements in a mapping, issuing ERC721 ids, or counting request ids.\n *\n * Include with `using Counters for Counters.Counter;`\n */\nlibrary Counters {\n struct Counter {\n // This variable should never be directly accessed by users of the library: interactions must be restricted to\n // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add\n // this feature: see https://github.com/ethereum/solidity/issues/4637\n uint256 _value; // default: 0\n }\n\n function current(Counter storage counter) internal view returns (uint256) {\n return counter._value;\n }\n\n function increment(Counter storage counter) internal {\n unchecked {\n counter._value += 1;\n }\n }\n\n function decrement(Counter storage counter) internal {\n uint256 value = counter._value;\n require(value > 0, \"Counter: decrement overflow\");\n unchecked {\n counter._value = value - 1;\n }\n }\n\n function reset(Counter storage counter) internal {\n counter._value = 0;\n }\n}\n" + }, + "@openzeppelin/contracts/utils/cryptography/ECDSA.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Strings.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 ECDSA {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // Deprecated in v4.8\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 }\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 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 /// @solidity memory-safe-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 {\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\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\", Strings.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/utils/cryptography/EIP712.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/EIP712.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./ECDSA.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 */\nabstract contract EIP712 {\n /* solhint-disable var-name-mixedcase */\n // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to\n // invalidate the cached domain separator if the chain id changes.\n bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;\n uint256 private immutable _CACHED_CHAIN_ID;\n address private immutable _CACHED_THIS;\n\n bytes32 private immutable _HASHED_NAME;\n bytes32 private immutable _HASHED_VERSION;\n bytes32 private immutable _TYPE_HASH;\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 constructor(string memory name, string memory version) {\n bytes32 hashedName = keccak256(bytes(name));\n bytes32 hashedVersion = keccak256(bytes(version));\n bytes32 typeHash = keccak256(\n \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n );\n _HASHED_NAME = hashedName;\n _HASHED_VERSION = hashedVersion;\n _CACHED_CHAIN_ID = block.chainid;\n _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);\n _CACHED_THIS = address(this);\n _TYPE_HASH = typeHash;\n }\n\n /**\n * @dev Returns the domain separator for the current chain.\n */\n function _domainSeparatorV4() internal view returns (bytes32) {\n if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {\n return _CACHED_DOMAIN_SEPARATOR;\n } else {\n return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);\n }\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 ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);\n }\n}\n" + }, + "@openzeppelin/contracts/utils/math/Math.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.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 //\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)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\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 unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/utils/math/SafeCast.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\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 uint248 from uint256, reverting on\n * overflow (when the input is greater than largest uint248).\n *\n * Counterpart to Solidity's `uint248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toUint248(uint256 value) internal pure returns (uint248) {\n require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n return uint248(value);\n }\n\n /**\n * @dev Returns the downcasted uint240 from uint256, reverting on\n * overflow (when the input is greater than largest uint240).\n *\n * Counterpart to Solidity's `uint240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toUint240(uint256 value) internal pure returns (uint240) {\n require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n return uint240(value);\n }\n\n /**\n * @dev Returns the downcasted uint232 from uint256, reverting on\n * overflow (when the input is greater than largest uint232).\n *\n * Counterpart to Solidity's `uint232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toUint232(uint256 value) internal pure returns (uint232) {\n require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n return uint232(value);\n }\n\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 * _Available since v4.2._\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint216 from uint256, reverting on\n * overflow (when the input is greater than largest uint216).\n *\n * Counterpart to Solidity's `uint216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toUint216(uint256 value) internal pure returns (uint216) {\n require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n return uint216(value);\n }\n\n /**\n * @dev Returns the downcasted uint208 from uint256, reverting on\n * overflow (when the input is greater than largest uint208).\n *\n * Counterpart to Solidity's `uint208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toUint208(uint256 value) internal pure returns (uint208) {\n require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n return uint208(value);\n }\n\n /**\n * @dev Returns the downcasted uint200 from uint256, reverting on\n * overflow (when the input is greater than largest uint200).\n *\n * Counterpart to Solidity's `uint200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toUint200(uint256 value) internal pure returns (uint200) {\n require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n return uint200(value);\n }\n\n /**\n * @dev Returns the downcasted uint192 from uint256, reverting on\n * overflow (when the input is greater than largest uint192).\n *\n * Counterpart to Solidity's `uint192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toUint192(uint256 value) internal pure returns (uint192) {\n require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n return uint192(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 uint176 from uint256, reverting on\n * overflow (when the input is greater than largest uint176).\n *\n * Counterpart to Solidity's `uint176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toUint176(uint256 value) internal pure returns (uint176) {\n require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n return uint176(value);\n }\n\n /**\n * @dev Returns the downcasted uint168 from uint256, reverting on\n * overflow (when the input is greater than largest uint168).\n *\n * Counterpart to Solidity's `uint168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toUint168(uint256 value) internal pure returns (uint168) {\n require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n return uint168(value);\n }\n\n /**\n * @dev Returns the downcasted uint160 from uint256, reverting on\n * overflow (when the input is greater than largest uint160).\n *\n * Counterpart to Solidity's `uint160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toUint160(uint256 value) internal pure returns (uint160) {\n require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n return uint160(value);\n }\n\n /**\n * @dev Returns the downcasted uint152 from uint256, reverting on\n * overflow (when the input is greater than largest uint152).\n *\n * Counterpart to Solidity's `uint152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toUint152(uint256 value) internal pure returns (uint152) {\n require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n return uint152(value);\n }\n\n /**\n * @dev Returns the downcasted uint144 from uint256, reverting on\n * overflow (when the input is greater than largest uint144).\n *\n * Counterpart to Solidity's `uint144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toUint144(uint256 value) internal pure returns (uint144) {\n require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n return uint144(value);\n }\n\n /**\n * @dev Returns the downcasted uint136 from uint256, reverting on\n * overflow (when the input is greater than largest uint136).\n *\n * Counterpart to Solidity's `uint136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toUint136(uint256 value) internal pure returns (uint136) {\n require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n return uint136(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 * _Available since v2.5._\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint120 from uint256, reverting on\n * overflow (when the input is greater than largest uint120).\n *\n * Counterpart to Solidity's `uint120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toUint120(uint256 value) internal pure returns (uint120) {\n require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n return uint120(value);\n }\n\n /**\n * @dev Returns the downcasted uint112 from uint256, reverting on\n * overflow (when the input is greater than largest uint112).\n *\n * Counterpart to Solidity's `uint112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toUint112(uint256 value) internal pure returns (uint112) {\n require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n return uint112(value);\n }\n\n /**\n * @dev Returns the downcasted uint104 from uint256, reverting on\n * overflow (when the input is greater than largest uint104).\n *\n * Counterpart to Solidity's `uint104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toUint104(uint256 value) internal pure returns (uint104) {\n require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n return uint104(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 * _Available since v4.2._\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint88 from uint256, reverting on\n * overflow (when the input is greater than largest uint88).\n *\n * Counterpart to Solidity's `uint88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toUint88(uint256 value) internal pure returns (uint88) {\n require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n return uint88(value);\n }\n\n /**\n * @dev Returns the downcasted uint80 from uint256, reverting on\n * overflow (when the input is greater than largest uint80).\n *\n * Counterpart to Solidity's `uint80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toUint80(uint256 value) internal pure returns (uint80) {\n require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n return uint80(value);\n }\n\n /**\n * @dev Returns the downcasted uint72 from uint256, reverting on\n * overflow (when the input is greater than largest uint72).\n *\n * Counterpart to Solidity's `uint72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toUint72(uint256 value) internal pure returns (uint72) {\n require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n return uint72(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 * _Available since v2.5._\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint56 from uint256, reverting on\n * overflow (when the input is greater than largest uint56).\n *\n * Counterpart to Solidity's `uint56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toUint56(uint256 value) internal pure returns (uint56) {\n require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n return uint56(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 uint40 from uint256, reverting on\n * overflow (when the input is greater than largest uint40).\n *\n * Counterpart to Solidity's `uint40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toUint40(uint256 value) internal pure returns (uint40) {\n require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n return uint40(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 * _Available since v2.5._\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint24 from uint256, reverting on\n * overflow (when the input is greater than largest uint24).\n *\n * Counterpart to Solidity's `uint24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toUint24(uint256 value) internal pure returns (uint24) {\n require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n return uint24(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 * _Available since v2.5._\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\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 * _Available since v2.5._\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\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 * _Available since v3.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 int248 from int256, reverting on\n * overflow (when the input is less than smallest int248 or\n * greater than largest int248).\n *\n * Counterpart to Solidity's `int248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toInt248(int256 value) internal pure returns (int248 downcasted) {\n downcasted = int248(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n }\n\n /**\n * @dev Returns the downcasted int240 from int256, reverting on\n * overflow (when the input is less than smallest int240 or\n * greater than largest int240).\n *\n * Counterpart to Solidity's `int240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toInt240(int256 value) internal pure returns (int240 downcasted) {\n downcasted = int240(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n }\n\n /**\n * @dev Returns the downcasted int232 from int256, reverting on\n * overflow (when the input is less than smallest int232 or\n * greater than largest int232).\n *\n * Counterpart to Solidity's `int232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toInt232(int256 value) internal pure returns (int232 downcasted) {\n downcasted = int232(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n }\n\n /**\n * @dev Returns the downcasted int224 from int256, reverting on\n * overflow (when the input is less than smallest int224 or\n * greater than largest int224).\n *\n * Counterpart to Solidity's `int224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.7._\n */\n function toInt224(int256 value) internal pure returns (int224 downcasted) {\n downcasted = int224(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n }\n\n /**\n * @dev Returns the downcasted int216 from int256, reverting on\n * overflow (when the input is less than smallest int216 or\n * greater than largest int216).\n *\n * Counterpart to Solidity's `int216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toInt216(int256 value) internal pure returns (int216 downcasted) {\n downcasted = int216(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n }\n\n /**\n * @dev Returns the downcasted int208 from int256, reverting on\n * overflow (when the input is less than smallest int208 or\n * greater than largest int208).\n *\n * Counterpart to Solidity's `int208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toInt208(int256 value) internal pure returns (int208 downcasted) {\n downcasted = int208(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n }\n\n /**\n * @dev Returns the downcasted int200 from int256, reverting on\n * overflow (when the input is less than smallest int200 or\n * greater than largest int200).\n *\n * Counterpart to Solidity's `int200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toInt200(int256 value) internal pure returns (int200 downcasted) {\n downcasted = int200(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n }\n\n /**\n * @dev Returns the downcasted int192 from int256, reverting on\n * overflow (when the input is less than smallest int192 or\n * greater than largest int192).\n *\n * Counterpart to Solidity's `int192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toInt192(int256 value) internal pure returns (int192 downcasted) {\n downcasted = int192(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n }\n\n /**\n * @dev Returns the downcasted int184 from int256, reverting on\n * overflow (when the input is less than smallest int184 or\n * greater than largest int184).\n *\n * Counterpart to Solidity's `int184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toInt184(int256 value) internal pure returns (int184 downcasted) {\n downcasted = int184(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n }\n\n /**\n * @dev Returns the downcasted int176 from int256, reverting on\n * overflow (when the input is less than smallest int176 or\n * greater than largest int176).\n *\n * Counterpart to Solidity's `int176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toInt176(int256 value) internal pure returns (int176 downcasted) {\n downcasted = int176(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n }\n\n /**\n * @dev Returns the downcasted int168 from int256, reverting on\n * overflow (when the input is less than smallest int168 or\n * greater than largest int168).\n *\n * Counterpart to Solidity's `int168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toInt168(int256 value) internal pure returns (int168 downcasted) {\n downcasted = int168(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n }\n\n /**\n * @dev Returns the downcasted int160 from int256, reverting on\n * overflow (when the input is less than smallest int160 or\n * greater than largest int160).\n *\n * Counterpart to Solidity's `int160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toInt160(int256 value) internal pure returns (int160 downcasted) {\n downcasted = int160(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n }\n\n /**\n * @dev Returns the downcasted int152 from int256, reverting on\n * overflow (when the input is less than smallest int152 or\n * greater than largest int152).\n *\n * Counterpart to Solidity's `int152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toInt152(int256 value) internal pure returns (int152 downcasted) {\n downcasted = int152(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n }\n\n /**\n * @dev Returns the downcasted int144 from int256, reverting on\n * overflow (when the input is less than smallest int144 or\n * greater than largest int144).\n *\n * Counterpart to Solidity's `int144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toInt144(int256 value) internal pure returns (int144 downcasted) {\n downcasted = int144(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n }\n\n /**\n * @dev Returns the downcasted int136 from int256, reverting on\n * overflow (when the input is less than smallest int136 or\n * greater than largest int136).\n *\n * Counterpart to Solidity's `int136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toInt136(int256 value) internal pure returns (int136 downcasted) {\n downcasted = int136(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\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 downcasted) {\n downcasted = int128(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n }\n\n /**\n * @dev Returns the downcasted int120 from int256, reverting on\n * overflow (when the input is less than smallest int120 or\n * greater than largest int120).\n *\n * Counterpart to Solidity's `int120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toInt120(int256 value) internal pure returns (int120 downcasted) {\n downcasted = int120(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n }\n\n /**\n * @dev Returns the downcasted int112 from int256, reverting on\n * overflow (when the input is less than smallest int112 or\n * greater than largest int112).\n *\n * Counterpart to Solidity's `int112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toInt112(int256 value) internal pure returns (int112 downcasted) {\n downcasted = int112(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n }\n\n /**\n * @dev Returns the downcasted int104 from int256, reverting on\n * overflow (when the input is less than smallest int104 or\n * greater than largest int104).\n *\n * Counterpart to Solidity's `int104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toInt104(int256 value) internal pure returns (int104 downcasted) {\n downcasted = int104(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n }\n\n /**\n * @dev Returns the downcasted int96 from int256, reverting on\n * overflow (when the input is less than smallest int96 or\n * greater than largest int96).\n *\n * Counterpart to Solidity's `int96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.7._\n */\n function toInt96(int256 value) internal pure returns (int96 downcasted) {\n downcasted = int96(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n }\n\n /**\n * @dev Returns the downcasted int88 from int256, reverting on\n * overflow (when the input is less than smallest int88 or\n * greater than largest int88).\n *\n * Counterpart to Solidity's `int88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toInt88(int256 value) internal pure returns (int88 downcasted) {\n downcasted = int88(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n }\n\n /**\n * @dev Returns the downcasted int80 from int256, reverting on\n * overflow (when the input is less than smallest int80 or\n * greater than largest int80).\n *\n * Counterpart to Solidity's `int80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toInt80(int256 value) internal pure returns (int80 downcasted) {\n downcasted = int80(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n }\n\n /**\n * @dev Returns the downcasted int72 from int256, reverting on\n * overflow (when the input is less than smallest int72 or\n * greater than largest int72).\n *\n * Counterpart to Solidity's `int72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toInt72(int256 value) internal pure returns (int72 downcasted) {\n downcasted = int72(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\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 downcasted) {\n downcasted = int64(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n }\n\n /**\n * @dev Returns the downcasted int56 from int256, reverting on\n * overflow (when the input is less than smallest int56 or\n * greater than largest int56).\n *\n * Counterpart to Solidity's `int56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toInt56(int256 value) internal pure returns (int56 downcasted) {\n downcasted = int56(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n }\n\n /**\n * @dev Returns the downcasted int48 from int256, reverting on\n * overflow (when the input is less than smallest int48 or\n * greater than largest int48).\n *\n * Counterpart to Solidity's `int48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toInt48(int256 value) internal pure returns (int48 downcasted) {\n downcasted = int48(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n }\n\n /**\n * @dev Returns the downcasted int40 from int256, reverting on\n * overflow (when the input is less than smallest int40 or\n * greater than largest int40).\n *\n * Counterpart to Solidity's `int40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toInt40(int256 value) internal pure returns (int40 downcasted) {\n downcasted = int40(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\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 downcasted) {\n downcasted = int32(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n }\n\n /**\n * @dev Returns the downcasted int24 from int256, reverting on\n * overflow (when the input is less than smallest int24 or\n * greater than largest int24).\n *\n * Counterpart to Solidity's `int24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toInt24(int256 value) internal pure returns (int24 downcasted) {\n downcasted = int24(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\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 downcasted) {\n downcasted = int16(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\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 downcasted) {\n downcasted = int8(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\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 * _Available since v3.0._\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(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }\n}\n" + }, + "@openzeppelin/contracts/utils/math/SafeMath.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol)\n\npragma solidity ^0.8.0;\n\n// CAUTION\n// This version of SafeMath should only be used with Solidity 0.8 or later,\n// because it relies on the compiler's built in overflow checks.\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations.\n *\n * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler\n * now has built in overflow checking.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n return a + b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n return a * b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator.\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n unchecked {\n require(b <= a, errorMessage);\n return a - b;\n }\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n unchecked {\n require(b > 0, errorMessage);\n return a / b;\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n unchecked {\n require(b > 0, errorMessage);\n return a % b;\n }\n }\n}\n" + }, + "@openzeppelin/contracts/utils/Strings.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\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 unchecked {\n uint256 length = Math.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\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 unchecked {\n return toHexString(value, Math.log256(value) + 1);\n }\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] = _SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n" + }, + "@openzeppelin/contracts/utils/structs/EnumerableSet.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping(bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) {\n // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n if (lastIndex != toDeleteIndex) {\n bytes32 lastValue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastValue;\n // Update the index for the moved value\n set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n }\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n return set._values[index];\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function _values(Set storage set) private view returns (bytes32[] memory) {\n return set._values;\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n bytes32[] memory store = _values(set._inner);\n bytes32[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(AddressSet storage set) internal view returns (address[] memory) {\n bytes32[] memory store = _values(set._inner);\n address[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(UintSet storage set) internal view returns (uint256[] memory) {\n bytes32[] memory store = _values(set._inner);\n uint256[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n}\n" + }, + "contracts/EAS/TellerAS.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"../Types.sol\";\nimport \"../interfaces/IEAS.sol\";\nimport \"../interfaces/IASRegistry.sol\";\n\n/**\n * @title TellerAS - Teller Attestation Service - based on EAS - Ethereum Attestation Service\n */\ncontract TellerAS is IEAS {\n error AccessDenied();\n error AlreadyRevoked();\n error InvalidAttestation();\n error InvalidExpirationTime();\n error InvalidOffset();\n error InvalidRegistry();\n error InvalidSchema();\n error InvalidVerifier();\n error NotFound();\n error NotPayable();\n\n string public constant VERSION = \"0.8\";\n\n // A terminator used when concatenating and hashing multiple fields.\n string private constant HASH_TERMINATOR = \"@\";\n\n // The AS global registry.\n IASRegistry private immutable _asRegistry;\n\n // The EIP712 verifier used to verify signed attestations.\n IEASEIP712Verifier private immutable _eip712Verifier;\n\n // A mapping between attestations and their related attestations.\n mapping(bytes32 => bytes32[]) private _relatedAttestations;\n\n // A mapping between an account and its received attestations.\n mapping(address => mapping(bytes32 => bytes32[]))\n private _receivedAttestations;\n\n // A mapping between an account and its sent attestations.\n mapping(address => mapping(bytes32 => bytes32[])) private _sentAttestations;\n\n // A mapping between a schema and its attestations.\n mapping(bytes32 => bytes32[]) private _schemaAttestations;\n\n // The global mapping between attestations and their UUIDs.\n mapping(bytes32 => Attestation) private _db;\n\n // The global counter for the total number of attestations.\n uint256 private _attestationsCount;\n\n bytes32 private _lastUUID;\n\n /**\n * @dev Creates a new EAS instance.\n *\n * @param registry The address of the global AS registry.\n * @param verifier The address of the EIP712 verifier.\n */\n constructor(IASRegistry registry, IEASEIP712Verifier verifier) {\n if (address(registry) == address(0x0)) {\n revert InvalidRegistry();\n }\n\n if (address(verifier) == address(0x0)) {\n revert InvalidVerifier();\n }\n\n _asRegistry = registry;\n _eip712Verifier = verifier;\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getASRegistry() external view override returns (IASRegistry) {\n return _asRegistry;\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getEIP712Verifier()\n external\n view\n override\n returns (IEASEIP712Verifier)\n {\n return _eip712Verifier;\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getAttestationsCount() external view override returns (uint256) {\n return _attestationsCount;\n }\n\n /**\n * @inheritdoc IEAS\n */\n function attest(\n address recipient,\n bytes32 schema,\n uint256 expirationTime,\n bytes32 refUUID,\n bytes calldata data\n ) public payable virtual override returns (bytes32) {\n return\n _attest(\n recipient,\n schema,\n expirationTime,\n refUUID,\n data,\n msg.sender\n );\n }\n\n /**\n * @inheritdoc IEAS\n */\n function attestByDelegation(\n address recipient,\n bytes32 schema,\n uint256 expirationTime,\n bytes32 refUUID,\n bytes calldata data,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public payable virtual override returns (bytes32) {\n _eip712Verifier.attest(\n recipient,\n schema,\n expirationTime,\n refUUID,\n data,\n attester,\n v,\n r,\n s\n );\n\n return\n _attest(recipient, schema, expirationTime, refUUID, data, attester);\n }\n\n /**\n * @inheritdoc IEAS\n */\n function revoke(bytes32 uuid) public virtual override {\n return _revoke(uuid, msg.sender);\n }\n\n /**\n * @inheritdoc IEAS\n */\n function revokeByDelegation(\n bytes32 uuid,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public virtual override {\n _eip712Verifier.revoke(uuid, attester, v, r, s);\n\n _revoke(uuid, attester);\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getAttestation(bytes32 uuid)\n external\n view\n override\n returns (Attestation memory)\n {\n return _db[uuid];\n }\n\n /**\n * @inheritdoc IEAS\n */\n function isAttestationValid(bytes32 uuid)\n public\n view\n override\n returns (bool)\n {\n return _db[uuid].uuid != 0;\n }\n\n /**\n * @inheritdoc IEAS\n */\n function isAttestationActive(bytes32 uuid)\n public\n view\n virtual\n override\n returns (bool)\n {\n return\n isAttestationValid(uuid) &&\n _db[uuid].expirationTime >= block.timestamp &&\n _db[uuid].revocationTime == 0;\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getReceivedAttestationUUIDs(\n address recipient,\n bytes32 schema,\n uint256 start,\n uint256 length,\n bool reverseOrder\n ) external view override returns (bytes32[] memory) {\n return\n _sliceUUIDs(\n _receivedAttestations[recipient][schema],\n start,\n length,\n reverseOrder\n );\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getReceivedAttestationUUIDsCount(address recipient, bytes32 schema)\n external\n view\n override\n returns (uint256)\n {\n return _receivedAttestations[recipient][schema].length;\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getSentAttestationUUIDs(\n address attester,\n bytes32 schema,\n uint256 start,\n uint256 length,\n bool reverseOrder\n ) external view override returns (bytes32[] memory) {\n return\n _sliceUUIDs(\n _sentAttestations[attester][schema],\n start,\n length,\n reverseOrder\n );\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getSentAttestationUUIDsCount(address recipient, bytes32 schema)\n external\n view\n override\n returns (uint256)\n {\n return _sentAttestations[recipient][schema].length;\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getRelatedAttestationUUIDs(\n bytes32 uuid,\n uint256 start,\n uint256 length,\n bool reverseOrder\n ) external view override returns (bytes32[] memory) {\n return\n _sliceUUIDs(\n _relatedAttestations[uuid],\n start,\n length,\n reverseOrder\n );\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getRelatedAttestationUUIDsCount(bytes32 uuid)\n external\n view\n override\n returns (uint256)\n {\n return _relatedAttestations[uuid].length;\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getSchemaAttestationUUIDs(\n bytes32 schema,\n uint256 start,\n uint256 length,\n bool reverseOrder\n ) external view override returns (bytes32[] memory) {\n return\n _sliceUUIDs(\n _schemaAttestations[schema],\n start,\n length,\n reverseOrder\n );\n }\n\n /**\n * @inheritdoc IEAS\n */\n function getSchemaAttestationUUIDsCount(bytes32 schema)\n external\n view\n override\n returns (uint256)\n {\n return _schemaAttestations[schema].length;\n }\n\n /**\n * @dev Attests to a specific AS.\n *\n * @param recipient The recipient of the attestation.\n * @param schema The UUID of the AS.\n * @param expirationTime The expiration time of the attestation.\n * @param refUUID An optional related attestation's UUID.\n * @param data Additional custom data.\n * @param attester The attesting account.\n *\n * @return The UUID of the new attestation.\n */\n function _attest(\n address recipient,\n bytes32 schema,\n uint256 expirationTime,\n bytes32 refUUID,\n bytes calldata data,\n address attester\n ) private returns (bytes32) {\n if (expirationTime <= block.timestamp) {\n revert InvalidExpirationTime();\n }\n\n IASRegistry.ASRecord memory asRecord = _asRegistry.getAS(schema);\n if (asRecord.uuid == EMPTY_UUID) {\n revert InvalidSchema();\n }\n\n IASResolver resolver = asRecord.resolver;\n if (address(resolver) != address(0x0)) {\n if (msg.value != 0 && !resolver.isPayable()) {\n revert NotPayable();\n }\n\n if (\n !resolver.resolve{ value: msg.value }(\n recipient,\n asRecord.schema,\n data,\n expirationTime,\n attester\n )\n ) {\n revert InvalidAttestation();\n }\n }\n\n Attestation memory attestation = Attestation({\n uuid: EMPTY_UUID,\n schema: schema,\n recipient: recipient,\n attester: attester,\n time: block.timestamp,\n expirationTime: expirationTime,\n revocationTime: 0,\n refUUID: refUUID,\n data: data\n });\n\n _lastUUID = _getUUID(attestation);\n attestation.uuid = _lastUUID;\n\n _receivedAttestations[recipient][schema].push(_lastUUID);\n _sentAttestations[attester][schema].push(_lastUUID);\n _schemaAttestations[schema].push(_lastUUID);\n\n _db[_lastUUID] = attestation;\n _attestationsCount++;\n\n if (refUUID != 0) {\n if (!isAttestationValid(refUUID)) {\n revert NotFound();\n }\n\n _relatedAttestations[refUUID].push(_lastUUID);\n }\n\n emit Attested(recipient, attester, _lastUUID, schema);\n\n return _lastUUID;\n }\n\n function getLastUUID() external view returns (bytes32) {\n return _lastUUID;\n }\n\n /**\n * @dev Revokes an existing attestation to a specific AS.\n *\n * @param uuid The UUID of the attestation to revoke.\n * @param attester The attesting account.\n */\n function _revoke(bytes32 uuid, address attester) private {\n Attestation storage attestation = _db[uuid];\n if (attestation.uuid == EMPTY_UUID) {\n revert NotFound();\n }\n\n if (attestation.attester != attester) {\n revert AccessDenied();\n }\n\n if (attestation.revocationTime != 0) {\n revert AlreadyRevoked();\n }\n\n attestation.revocationTime = block.timestamp;\n\n emit Revoked(attestation.recipient, attester, uuid, attestation.schema);\n }\n\n /**\n * @dev Calculates a UUID for a given attestation.\n *\n * @param attestation The input attestation.\n *\n * @return Attestation UUID.\n */\n function _getUUID(Attestation memory attestation)\n private\n view\n returns (bytes32)\n {\n return\n keccak256(\n abi.encodePacked(\n attestation.schema,\n attestation.recipient,\n attestation.attester,\n attestation.time,\n attestation.expirationTime,\n attestation.data,\n HASH_TERMINATOR,\n _attestationsCount\n )\n );\n }\n\n /**\n * @dev Returns a slice in an array of attestation UUIDs.\n *\n * @param uuids The array of attestation UUIDs.\n * @param start The offset to start from.\n * @param length The number of total members to retrieve.\n * @param reverseOrder Whether the offset starts from the end and the data is returned in reverse.\n *\n * @return An array of attestation UUIDs.\n */\n function _sliceUUIDs(\n bytes32[] memory uuids,\n uint256 start,\n uint256 length,\n bool reverseOrder\n ) private pure returns (bytes32[] memory) {\n uint256 attestationsLength = uuids.length;\n if (attestationsLength == 0) {\n return new bytes32[](0);\n }\n\n if (start >= attestationsLength) {\n revert InvalidOffset();\n }\n\n uint256 len = length;\n if (attestationsLength < start + length) {\n len = attestationsLength - start;\n }\n\n bytes32[] memory res = new bytes32[](len);\n\n for (uint256 i = 0; i < len; ++i) {\n res[i] = uuids[\n reverseOrder ? attestationsLength - (start + i + 1) : start + i\n ];\n }\n\n return res;\n }\n}\n" + }, + "contracts/ERC2771ContextUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (metatx/ERC2771Context.sol)\n\npragma solidity ^0.8.9;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Context variant with ERC2771 support.\n * @dev This is modified from the OZ library to remove the gap of storage variables at the end.\n */\nabstract contract ERC2771ContextUpgradeable is\n Initializable,\n ContextUpgradeable\n{\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address private immutable _trustedForwarder;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address trustedForwarder) {\n _trustedForwarder = trustedForwarder;\n }\n\n function isTrustedForwarder(address forwarder)\n public\n view\n virtual\n returns (bool)\n {\n return forwarder == _trustedForwarder;\n }\n\n function _msgSender()\n internal\n view\n virtual\n override\n returns (address sender)\n {\n if (isTrustedForwarder(msg.sender)) {\n // The assembly code is more direct than the Solidity version using `abi.decode`.\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n } else {\n return super._msgSender();\n }\n }\n\n function _msgData()\n internal\n view\n virtual\n override\n returns (bytes calldata)\n {\n if (isTrustedForwarder(msg.sender)) {\n return msg.data[:msg.data.length - 20];\n } else {\n return super._msgData();\n }\n }\n}\n" + }, + "contracts/interfaces/escrow/ICollateralEscrowV1.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\nenum CollateralType {\n ERC20,\n ERC721,\n ERC1155\n}\n\nstruct Collateral {\n CollateralType _collateralType;\n uint256 _amount;\n uint256 _tokenId;\n address _collateralAddress;\n}\n\ninterface ICollateralEscrowV1 {\n /**\n * @notice Deposits a collateral asset into the escrow.\n * @param _collateralType The type of collateral asset to deposit (ERC721, ERC1155).\n * @param _collateralAddress The address of the collateral token.i feel\n * @param _amount The amount to deposit.\n */\n function depositAsset(\n CollateralType _collateralType,\n address _collateralAddress,\n uint256 _amount,\n uint256 _tokenId\n ) external payable;\n\n /**\n * @notice Withdraws a collateral asset from the escrow.\n * @param _collateralAddress The address of the collateral contract.\n * @param _amount The amount to withdraw.\n * @param _recipient The address to send the assets to.\n */\n function withdraw(\n address _collateralAddress,\n uint256 _amount,\n address _recipient\n ) external;\n\n function withdrawDustTokens( \n address _tokenAddress, \n uint256 _amount,\n address _recipient\n ) external;\n\n\n function getBid() external view returns (uint256);\n\n function initialize(uint256 _bidId) external;\n\n\n}\n" + }, + "contracts/interfaces/IASRegistry.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./IASResolver.sol\";\n\n/**\n * @title The global AS registry interface.\n */\ninterface IASRegistry {\n /**\n * @title A struct representing a record for a submitted AS (Attestation Schema).\n */\n struct ASRecord {\n // A unique identifier of the AS.\n bytes32 uuid;\n // Optional schema resolver.\n IASResolver resolver;\n // Auto-incrementing index for reference, assigned by the registry itself.\n uint256 index;\n // Custom specification of the AS (e.g., an ABI).\n bytes schema;\n }\n\n /**\n * @dev Triggered when a new AS has been registered\n *\n * @param uuid The AS UUID.\n * @param index The AS index.\n * @param schema The AS schema.\n * @param resolver An optional AS schema resolver.\n * @param attester The address of the account used to register the AS.\n */\n event Registered(\n bytes32 indexed uuid,\n uint256 indexed index,\n bytes schema,\n IASResolver resolver,\n address attester\n );\n\n /**\n * @dev Submits and reserve a new AS\n *\n * @param schema The AS data schema.\n * @param resolver An optional AS schema resolver.\n *\n * @return The UUID of the new AS.\n */\n function register(bytes calldata schema, IASResolver resolver)\n external\n returns (bytes32);\n\n /**\n * @dev Returns an existing AS by UUID\n *\n * @param uuid The UUID of the AS to retrieve.\n *\n * @return The AS data members.\n */\n function getAS(bytes32 uuid) external view returns (ASRecord memory);\n\n /**\n * @dev Returns the global counter for the total number of attestations\n *\n * @return The global counter for the total number of attestations.\n */\n function getASCount() external view returns (uint256);\n}\n" + }, + "contracts/interfaces/IASResolver.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n\n// SPDX-License-Identifier: MIT\n\n/**\n * @title The interface of an optional AS resolver.\n */\ninterface IASResolver {\n /**\n * @dev Returns whether the resolver supports ETH transfers\n */\n function isPayable() external pure returns (bool);\n\n /**\n * @dev Resolves an attestation and verifier whether its data conforms to the spec.\n *\n * @param recipient The recipient of the attestation.\n * @param schema The AS data schema.\n * @param data The actual attestation data.\n * @param expirationTime The expiration time of the attestation.\n * @param msgSender The sender of the original attestation message.\n *\n * @return Whether the data is valid according to the scheme.\n */\n function resolve(\n address recipient,\n bytes calldata schema,\n bytes calldata data,\n uint256 expirationTime,\n address msgSender\n ) external payable returns (bool);\n}\n" + }, + "contracts/interfaces/ICollateralManager.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\nimport { Collateral } from \"./escrow/ICollateralEscrowV1.sol\";\n\ninterface ICollateralManager {\n /**\n * @notice Checks the validity of a borrower's collateral balance.\n * @param _bidId The id of the associated bid.\n * @param _collateralInfo Additional information about the collateral asset.\n * @return validation_ Boolean indicating if the collateral balance was validated.\n */\n function commitCollateral(\n uint256 _bidId,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validation_);\n\n /**\n * @notice Checks the validity of a borrower's collateral balance and commits it to a bid.\n * @param _bidId The id of the associated bid.\n * @param _collateralInfo Additional information about the collateral asset.\n * @return validation_ Boolean indicating if the collateral balance was validated.\n */\n function commitCollateral(\n uint256 _bidId,\n Collateral calldata _collateralInfo\n ) external returns (bool validation_);\n\n function checkBalances(\n address _borrowerAddress,\n Collateral[] calldata _collateralInfo\n ) external returns (bool validated_, bool[] memory checks_);\n\n /**\n * @notice Deploys a new collateral escrow.\n * @param _bidId The associated bidId of the collateral escrow.\n */\n function deployAndDeposit(uint256 _bidId) external;\n\n /**\n * @notice Gets the address of a deployed escrow.\n * @notice _bidId The bidId to return the escrow for.\n * @return The address of the escrow.\n */\n function getEscrow(uint256 _bidId) external view returns (address);\n\n /**\n * @notice Gets the collateral info for a given bid id.\n * @param _bidId The bidId to return the collateral info for.\n * @return The stored collateral info.\n */\n function getCollateralInfo(uint256 _bidId)\n external\n view\n returns (Collateral[] memory);\n\n function getCollateralAmount(uint256 _bidId, address collateralAssetAddress)\n external\n view\n returns (uint256 _amount);\n\n /**\n * @notice Withdraws deposited collateral from the created escrow of a bid.\n * @param _bidId The id of the bid to withdraw collateral for.\n */\n function withdraw(uint256 _bidId) external;\n\n /**\n * @notice Re-checks the validity of a borrower's collateral balance committed to a bid.\n * @param _bidId The id of the associated bid.\n * @return validation_ Boolean indicating if the collateral balance was validated.\n */\n function revalidateCollateral(uint256 _bidId) external returns (bool);\n\n /**\n * @notice Sends the deposited collateral to a lender of a bid.\n * @notice Can only be called by the protocol.\n * @param _bidId The id of the liquidated bid.\n */\n function lenderClaimCollateral(uint256 _bidId) external;\n\n\n\n /**\n * @notice Sends the deposited collateral to a lender of a bid.\n * @notice Can only be called by the protocol.\n * @param _bidId The id of the liquidated bid.\n * @param _collateralRecipient the address that will receive the collateral \n */\n function lenderClaimCollateralWithRecipient(uint256 _bidId, address _collateralRecipient) external;\n\n\n /**\n * @notice Sends the deposited collateral to a liquidator of a bid.\n * @notice Can only be called by the protocol.\n * @param _bidId The id of the liquidated bid.\n * @param _liquidatorAddress The address of the liquidator to send the collateral to.\n */\n function liquidateCollateral(uint256 _bidId, address _liquidatorAddress)\n external;\n}\n" + }, + "contracts/interfaces/IEAS.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./IASRegistry.sol\";\nimport \"./IEASEIP712Verifier.sol\";\n\n/**\n * @title EAS - Ethereum Attestation Service interface\n */\ninterface IEAS {\n /**\n * @dev A struct representing a single attestation.\n */\n struct Attestation {\n // A unique identifier of the attestation.\n bytes32 uuid;\n // A unique identifier of the AS.\n bytes32 schema;\n // The recipient of the attestation.\n address recipient;\n // The attester/sender of the attestation.\n address attester;\n // The time when the attestation was created (Unix timestamp).\n uint256 time;\n // The time when the attestation expires (Unix timestamp).\n uint256 expirationTime;\n // The time when the attestation was revoked (Unix timestamp).\n uint256 revocationTime;\n // The UUID of the related attestation.\n bytes32 refUUID;\n // Custom attestation data.\n bytes data;\n }\n\n /**\n * @dev Triggered when an attestation has been made.\n *\n * @param recipient The recipient of the attestation.\n * @param attester The attesting account.\n * @param uuid The UUID the revoked attestation.\n * @param schema The UUID of the AS.\n */\n event Attested(\n address indexed recipient,\n address indexed attester,\n bytes32 uuid,\n bytes32 indexed schema\n );\n\n /**\n * @dev Triggered when an attestation has been revoked.\n *\n * @param recipient The recipient of the attestation.\n * @param attester The attesting account.\n * @param schema The UUID of the AS.\n * @param uuid The UUID the revoked attestation.\n */\n event Revoked(\n address indexed recipient,\n address indexed attester,\n bytes32 uuid,\n bytes32 indexed schema\n );\n\n /**\n * @dev Returns the address of the AS global registry.\n *\n * @return The address of the AS global registry.\n */\n function getASRegistry() external view returns (IASRegistry);\n\n /**\n * @dev Returns the address of the EIP712 verifier used to verify signed attestations.\n *\n * @return The address of the EIP712 verifier used to verify signed attestations.\n */\n function getEIP712Verifier() external view returns (IEASEIP712Verifier);\n\n /**\n * @dev Returns the global counter for the total number of attestations.\n *\n * @return The global counter for the total number of attestations.\n */\n function getAttestationsCount() external view returns (uint256);\n\n /**\n * @dev Attests to a specific AS.\n *\n * @param recipient The recipient of the attestation.\n * @param schema The UUID of the AS.\n * @param expirationTime The expiration time of the attestation.\n * @param refUUID An optional related attestation's UUID.\n * @param data Additional custom data.\n *\n * @return The UUID of the new attestation.\n */\n function attest(\n address recipient,\n bytes32 schema,\n uint256 expirationTime,\n bytes32 refUUID,\n bytes calldata data\n ) external payable returns (bytes32);\n\n /**\n * @dev Attests to a specific AS using a provided EIP712 signature.\n *\n * @param recipient The recipient of the attestation.\n * @param schema The UUID of the AS.\n * @param expirationTime The expiration time of the attestation.\n * @param refUUID An optional related attestation's UUID.\n * @param data Additional custom data.\n * @param attester The attesting account.\n * @param v The recovery ID.\n * @param r The x-coordinate of the nonce R.\n * @param s The signature data.\n *\n * @return The UUID of the new attestation.\n */\n function attestByDelegation(\n address recipient,\n bytes32 schema,\n uint256 expirationTime,\n bytes32 refUUID,\n bytes calldata data,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external payable returns (bytes32);\n\n /**\n * @dev Revokes an existing attestation to a specific AS.\n *\n * @param uuid The UUID of the attestation to revoke.\n */\n function revoke(bytes32 uuid) external;\n\n /**\n * @dev Attests to a specific AS using a provided EIP712 signature.\n *\n * @param uuid The UUID of the attestation to revoke.\n * @param attester The attesting account.\n * @param v The recovery ID.\n * @param r The x-coordinate of the nonce R.\n * @param s The signature data.\n */\n function revokeByDelegation(\n bytes32 uuid,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns an existing attestation by UUID.\n *\n * @param uuid The UUID of the attestation to retrieve.\n *\n * @return The attestation data members.\n */\n function getAttestation(bytes32 uuid)\n external\n view\n returns (Attestation memory);\n\n /**\n * @dev Checks whether an attestation exists.\n *\n * @param uuid The UUID of the attestation to retrieve.\n *\n * @return Whether an attestation exists.\n */\n function isAttestationValid(bytes32 uuid) external view returns (bool);\n\n /**\n * @dev Checks whether an attestation is active.\n *\n * @param uuid The UUID of the attestation to retrieve.\n *\n * @return Whether an attestation is active.\n */\n function isAttestationActive(bytes32 uuid) external view returns (bool);\n\n /**\n * @dev Returns all received attestation UUIDs.\n *\n * @param recipient The recipient of the attestation.\n * @param schema The UUID of the AS.\n * @param start The offset to start from.\n * @param length The number of total members to retrieve.\n * @param reverseOrder Whether the offset starts from the end and the data is returned in reverse.\n *\n * @return An array of attestation UUIDs.\n */\n function getReceivedAttestationUUIDs(\n address recipient,\n bytes32 schema,\n uint256 start,\n uint256 length,\n bool reverseOrder\n ) external view returns (bytes32[] memory);\n\n /**\n * @dev Returns the number of received attestation UUIDs.\n *\n * @param recipient The recipient of the attestation.\n * @param schema The UUID of the AS.\n *\n * @return The number of attestations.\n */\n function getReceivedAttestationUUIDsCount(address recipient, bytes32 schema)\n external\n view\n returns (uint256);\n\n /**\n * @dev Returns all sent attestation UUIDs.\n *\n * @param attester The attesting account.\n * @param schema The UUID of the AS.\n * @param start The offset to start from.\n * @param length The number of total members to retrieve.\n * @param reverseOrder Whether the offset starts from the end and the data is returned in reverse.\n *\n * @return An array of attestation UUIDs.\n */\n function getSentAttestationUUIDs(\n address attester,\n bytes32 schema,\n uint256 start,\n uint256 length,\n bool reverseOrder\n ) external view returns (bytes32[] memory);\n\n /**\n * @dev Returns the number of sent attestation UUIDs.\n *\n * @param recipient The recipient of the attestation.\n * @param schema The UUID of the AS.\n *\n * @return The number of attestations.\n */\n function getSentAttestationUUIDsCount(address recipient, bytes32 schema)\n external\n view\n returns (uint256);\n\n /**\n * @dev Returns all attestations related to a specific attestation.\n *\n * @param uuid The UUID of the attestation to retrieve.\n * @param start The offset to start from.\n * @param length The number of total members to retrieve.\n * @param reverseOrder Whether the offset starts from the end and the data is returned in reverse.\n *\n * @return An array of attestation UUIDs.\n */\n function getRelatedAttestationUUIDs(\n bytes32 uuid,\n uint256 start,\n uint256 length,\n bool reverseOrder\n ) external view returns (bytes32[] memory);\n\n /**\n * @dev Returns the number of related attestation UUIDs.\n *\n * @param uuid The UUID of the attestation to retrieve.\n *\n * @return The number of related attestations.\n */\n function getRelatedAttestationUUIDsCount(bytes32 uuid)\n external\n view\n returns (uint256);\n\n /**\n * @dev Returns all per-schema attestation UUIDs.\n *\n * @param schema The UUID of the AS.\n * @param start The offset to start from.\n * @param length The number of total members to retrieve.\n * @param reverseOrder Whether the offset starts from the end and the data is returned in reverse.\n *\n * @return An array of attestation UUIDs.\n */\n function getSchemaAttestationUUIDs(\n bytes32 schema,\n uint256 start,\n uint256 length,\n bool reverseOrder\n ) external view returns (bytes32[] memory);\n\n /**\n * @dev Returns the number of per-schema attestation UUIDs.\n *\n * @param schema The UUID of the AS.\n *\n * @return The number of attestations.\n */\n function getSchemaAttestationUUIDsCount(bytes32 schema)\n external\n view\n returns (uint256);\n}\n" + }, + "contracts/interfaces/IEASEIP712Verifier.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n\n// SPDX-License-Identifier: MIT\n\n/**\n * @title EIP712 typed signatures verifier for EAS delegated attestations interface.\n */\ninterface IEASEIP712Verifier {\n /**\n * @dev Returns the current nonce per-account.\n *\n * @param account The requested accunt.\n *\n * @return The current nonce.\n */\n function getNonce(address account) external view returns (uint256);\n\n /**\n * @dev Verifies signed attestation.\n *\n * @param recipient The recipient of the attestation.\n * @param schema The UUID of the AS.\n * @param expirationTime The expiration time of the attestation.\n * @param refUUID An optional related attestation's UUID.\n * @param data Additional custom data.\n * @param attester The attesting account.\n * @param v The recovery ID.\n * @param r The x-coordinate of the nonce R.\n * @param s The signature data.\n */\n function attest(\n address recipient,\n bytes32 schema,\n uint256 expirationTime,\n bytes32 refUUID,\n bytes calldata data,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Verifies signed revocations.\n *\n * @param uuid The UUID of the attestation to revoke.\n * @param attester The attesting account.\n * @param v The recovery ID.\n * @param r The x-coordinate of the nonce R.\n * @param s The signature data.\n */\n function revoke(\n bytes32 uuid,\n address attester,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n}\n" + }, + "contracts/interfaces/IEscrowVault.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IEscrowVault {\n /**\n * @notice Deposit tokens on behalf of another account\n * @param account The address of the account\n * @param token The address of the token\n * @param amount The amount to increase the balance\n */\n function deposit(address account, address token, uint256 amount) external;\n\n function withdraw(address token, uint256 amount) external ;\n}\n" + }, + "contracts/interfaces/IExtensionsContext.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IExtensionsContext {\n function hasExtension(address extension, address account)\n external\n view\n returns (bool);\n\n function addExtension(address extension) external;\n\n function revokeExtension(address extension) external;\n}\n" + }, + "contracts/interfaces/IFlashRolloverLoan_G4.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IFlashRolloverLoan_G4 {\n struct RolloverCallbackArgs {\n address lenderCommitmentForwarder;\n uint256 loanId;\n address borrower;\n uint256 borrowerAmount;\n bytes acceptCommitmentArgs;\n }\n}\n" + }, + "contracts/interfaces/IHasProtocolPausingManager.sol": { + "content": "\n\n\n\n\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n//records the unpause timestamp s\ninterface IHasProtocolPausingManager {\n \n \n function getProtocolPausingManager() external view returns (address); \n\n // function isPauser(address _address) external view returns (bool); \n\n\n}\n" + }, + "contracts/interfaces/ILenderCommitmentForwarder_U1.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ILenderCommitmentForwarder_U1 {\n enum CommitmentCollateralType {\n NONE, // no collateral required\n ERC20,\n ERC721,\n ERC1155,\n ERC721_ANY_ID,\n ERC1155_ANY_ID,\n ERC721_MERKLE_PROOF,\n ERC1155_MERKLE_PROOF\n }\n\n /**\n * @notice Details about a lender's capital commitment.\n * @param maxPrincipal Amount of tokens being committed by the lender. Max amount that can be loaned.\n * @param expiration Expiration time in seconds, when the commitment expires.\n * @param maxDuration Length of time, in seconds that the lender's capital can be lent out for.\n * @param minInterestRate Minimum Annual percentage to be applied for loans using the lender's capital.\n * @param collateralTokenAddress The address for the token contract that must be used to provide collateral for loans for this commitment.\n * @param maxPrincipalPerCollateralAmount The amount of principal that can be used for a loan per each unit of collateral, expanded additionally by principal decimals.\n * @param collateralTokenType The type of asset of the collateralTokenAddress (ERC20, ERC721, or ERC1155).\n * @param lender The address of the lender for this commitment.\n * @param marketId The market id for this commitment.\n * @param principalTokenAddress The address for the token contract that will be used to provide principal for loans of this commitment.\n */\n struct Commitment {\n uint256 maxPrincipal;\n uint32 expiration;\n uint32 maxDuration;\n uint16 minInterestRate;\n address collateralTokenAddress;\n uint256 collateralTokenId; //we use this for the MerkleRootHash for type ERC721_MERKLE_PROOF\n uint256 maxPrincipalPerCollateralAmount;\n CommitmentCollateralType collateralTokenType;\n address lender;\n uint256 marketId;\n address principalTokenAddress;\n }\n\n struct PoolRouteConfig {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n }\n\n // mapping(uint256 => Commitment) public commitments;\n\n function getCommitmentMarketId(uint256 _commitmentId)\n external\n view\n returns (uint256);\n\n function getCommitmentLender(uint256 _commitmentId)\n external\n view\n returns (address);\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n external\n view\n returns (uint256);\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n external\n view\n returns (uint256);\n\n function createCommitmentWithUniswap(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList,\n PoolRouteConfig[] calldata _poolRoutes,\n uint16 _poolOracleLtvRatio\n ) external returns (uint256);\n\n function acceptCommitmentWithRecipient(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration\n ) external returns (uint256 bidId_);\n\n function acceptCommitmentWithRecipientAndProof(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration,\n bytes32[] calldata _merkleProof\n ) external returns (uint256 bidId_);\n\n\n function getCommitmentPrincipalTokenAddress(uint256 _commitmentId)\n external\n view\n returns (address);\n\n function getCommitmentCollateralTokenAddress(uint256 _commitmentId)\n external\n view\n returns (address);\n\n\n}\n" + }, + "contracts/interfaces/ILenderCommitmentForwarder_U2.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\nimport \"./IUniswapPricingLibrary.sol\";\n\ninterface ILenderCommitmentForwarder_U2 {\n enum CommitmentCollateralType {\n NONE, // no collateral required\n ERC20,\n ERC721,\n ERC1155,\n ERC721_ANY_ID,\n ERC1155_ANY_ID,\n ERC721_MERKLE_PROOF,\n ERC1155_MERKLE_PROOF\n }\n\n /**\n * @notice Details about a lender's capital commitment.\n * @param maxPrincipal Amount of tokens being committed by the lender. Max amount that can be loaned.\n * @param expiration Expiration time in seconds, when the commitment expires.\n * @param maxDuration Length of time, in seconds that the lender's capital can be lent out for.\n * @param minInterestRate Minimum Annual percentage to be applied for loans using the lender's capital.\n * @param collateralTokenAddress The address for the token contract that must be used to provide collateral for loans for this commitment.\n * @param maxPrincipalPerCollateralAmount The amount of principal that can be used for a loan per each unit of collateral, expanded additionally by principal decimals.\n * @param collateralTokenType The type of asset of the collateralTokenAddress (ERC20, ERC721, or ERC1155).\n * @param lender The address of the lender for this commitment.\n * @param marketId The market id for this commitment.\n * @param principalTokenAddress The address for the token contract that will be used to provide principal for loans of this commitment.\n */\n struct Commitment {\n uint256 maxPrincipal;\n uint32 expiration;\n uint32 maxDuration;\n uint16 minInterestRate;\n address collateralTokenAddress;\n uint256 collateralTokenId; //we use this for the MerkleRootHash for type ERC721_MERKLE_PROOF\n uint256 maxPrincipalPerCollateralAmount;\n CommitmentCollateralType collateralTokenType;\n address lender;\n uint256 marketId;\n address principalTokenAddress;\n }\n \n\n // mapping(uint256 => Commitment) public commitments;\n\n function getCommitmentMarketId(uint256 _commitmentId)\n external\n view\n returns (uint256);\n\n function getCommitmentLender(uint256 _commitmentId)\n external\n view\n returns (address);\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n external\n view\n returns (uint256);\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n external\n view\n returns (uint256);\n\n function createCommitmentWithUniswap(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolRoutes,\n uint16 _poolOracleLtvRatio\n ) external returns (uint256);\n\n function acceptCommitmentWithRecipient(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration\n ) external returns (uint256 bidId_);\n\n function acceptCommitmentWithRecipientAndProof(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration,\n bytes32[] calldata _merkleProof\n ) external returns (uint256 bidId_);\n\n\n function getCommitmentPrincipalTokenAddress(uint256 _commitmentId)\n external\n view\n returns (address);\n\n function getCommitmentCollateralTokenAddress(uint256 _commitmentId)\n external\n view\n returns (address);\n\n\n}\n" + }, + "contracts/interfaces/ILenderCommitmentForwarder.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ILenderCommitmentForwarder {\n enum CommitmentCollateralType {\n NONE, // no collateral required\n ERC20,\n ERC721,\n ERC1155,\n ERC721_ANY_ID,\n ERC1155_ANY_ID,\n ERC721_MERKLE_PROOF,\n ERC1155_MERKLE_PROOF\n }\n\n /**\n * @notice Details about a lender's capital commitment.\n * @param maxPrincipal Amount of tokens being committed by the lender. Max amount that can be loaned.\n * @param expiration Expiration time in seconds, when the commitment expires.\n * @param maxDuration Length of time, in seconds that the lender's capital can be lent out for.\n * @param minInterestRate Minimum Annual percentage to be applied for loans using the lender's capital.\n * @param collateralTokenAddress The address for the token contract that must be used to provide collateral for loans for this commitment.\n * @param maxPrincipalPerCollateralAmount The amount of principal that can be used for a loan per each unit of collateral, expanded additionally by principal decimals.\n * @param collateralTokenType The type of asset of the collateralTokenAddress (ERC20, ERC721, or ERC1155).\n * @param lender The address of the lender for this commitment.\n * @param marketId The market id for this commitment.\n * @param principalTokenAddress The address for the token contract that will be used to provide principal for loans of this commitment.\n */\n struct Commitment {\n uint256 maxPrincipal;\n uint32 expiration;\n uint32 maxDuration;\n uint16 minInterestRate;\n address collateralTokenAddress;\n uint256 collateralTokenId; //we use this for the MerkleRootHash for type ERC721_MERKLE_PROOF\n uint256 maxPrincipalPerCollateralAmount;\n CommitmentCollateralType collateralTokenType;\n address lender;\n uint256 marketId;\n address principalTokenAddress;\n }\n\n // mapping(uint256 => Commitment) public commitments;\n\n function getCommitmentMarketId(uint256 _commitmentId)\n external\n view\n returns (uint256);\n\n function getCommitmentLender(uint256 _commitmentId)\n external\n view\n returns (address);\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n external\n view\n returns (uint256);\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n external\n view\n returns (uint256);\n\n function createCommitment(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList\n ) external returns (uint256);\n\n function acceptCommitmentWithRecipient(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration\n ) external returns (uint256 bidId_);\n \n\n function acceptCommitmentWithRecipientAndProof(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration,\n bytes32[] calldata _merkleProof\n ) external returns (uint256 bidId_);\n}\n" + }, + "contracts/interfaces/ILenderCommitmentGroup.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\ninterface ILenderCommitmentGroup {\n\n\n\n struct CommitmentGroupConfig {\n address principalTokenAddress;\n address collateralTokenAddress;\n uint256 marketId;\n uint32 maxLoanDuration;\n uint16 interestRateLowerBound;\n uint16 interestRateUpperBound;\n uint16 liquidityThresholdPercent;\n uint16 collateralRatio; //essentially the overcollateralization ratio. 10000 is 1:1 baseline ?\n \n }\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n )\n external\n returns (\n //uint256 _maxPrincipalPerCollateralAmount //use oracle instead\n\n //ILenderCommitmentForwarder.Commitment calldata _createCommitmentArgs\n\n address poolSharesToken\n );\n\n function addPrincipalToCommitmentGroup(\n uint256 _amount,\n address _sharesRecipient,\n uint256 _minAmountOut\n ) external returns (uint256 sharesAmount_);\n\n\n\n function prepareSharesForBurn(\n uint256 _amountPoolSharesTokens \n ) external returns (bool);\n\n function burnSharesToWithdrawEarnings(\n uint256 _amountPoolSharesTokens,\n address _recipient,\n uint256 _minAmountOut\n ) external returns (uint256);\n\n\n function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external ;\n\n function getTokenDifferenceFromLiquidations() external view returns (int256);\n\n}\n" + }, + "contracts/interfaces/ILenderManager.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n\n// SPDX-License-Identifier: MIT\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol\";\n\nabstract contract ILenderManager is IERC721Upgradeable {\n /**\n * @notice Registers a new active lender for a loan, minting the nft.\n * @param _bidId The id for the loan to set.\n * @param _newLender The address of the new active lender.\n */\n function registerLoan(uint256 _bidId, address _newLender) external virtual;\n}\n" + }, + "contracts/interfaces/ILoanRepaymentCallbacks.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\n//tellerv2 should support this\ninterface ILoanRepaymentCallbacks {\n function setRepaymentListenerForBid(uint256 _bidId, address _listener)\n external;\n\n function getRepaymentListenerForBid(uint256 _bidId)\n external\n view\n returns (address);\n}\n" + }, + "contracts/interfaces/ILoanRepaymentListener.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ILoanRepaymentListener {\n function repayLoanCallback(\n uint256 bidId,\n address repayer,\n uint256 principalAmount,\n uint256 interestAmount\n ) external;\n}\n" + }, + "contracts/interfaces/IMarketRegistry.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../EAS/TellerAS.sol\";\nimport { PaymentType, PaymentCycleType } from \"../libraries/V2Calculations.sol\";\n\ninterface IMarketRegistry {\n function initialize(TellerAS tellerAs) external;\n\n function isVerifiedLender(uint256 _marketId, address _lender)\n external\n view\n returns (bool, bytes32);\n\n function isMarketOpen(uint256 _marketId) external view returns (bool);\n\n function isMarketClosed(uint256 _marketId) external view returns (bool);\n\n function isVerifiedBorrower(uint256 _marketId, address _borrower)\n external\n view\n returns (bool, bytes32);\n\n function getMarketOwner(uint256 _marketId) external view returns (address);\n\n function getMarketFeeRecipient(uint256 _marketId)\n external\n view\n returns (address);\n\n function getMarketURI(uint256 _marketId)\n external\n view\n returns (string memory);\n\n function getPaymentCycle(uint256 _marketId)\n external\n view\n returns (uint32, PaymentCycleType);\n\n function getPaymentDefaultDuration(uint256 _marketId)\n external\n view\n returns (uint32);\n\n function getBidExpirationTime(uint256 _marketId)\n external\n view\n returns (uint32);\n\n function getMarketplaceFee(uint256 _marketId)\n external\n view\n returns (uint16);\n\n function getPaymentType(uint256 _marketId)\n external\n view\n returns (PaymentType);\n\n function createMarket(\n address _initialOwner,\n uint32 _paymentCycleDuration,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _requireLenderAttestation,\n bool _requireBorrowerAttestation,\n PaymentType _paymentType,\n PaymentCycleType _paymentCycleType,\n string calldata _uri\n ) external returns (uint256 marketId_);\n\n function createMarket(\n address _initialOwner,\n uint32 _paymentCycleDuration,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _requireLenderAttestation,\n bool _requireBorrowerAttestation,\n string calldata _uri\n ) external returns (uint256 marketId_);\n\n function closeMarket(uint256 _marketId) external;\n}\n" + }, + "contracts/interfaces/IPausableTimestamp.sol": { + "content": "\n\n\n\n\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n//records the unpause timestamp s\ninterface IPausableTimestamp {\n \n \n function getLastUnpausedAt() \n external view \n returns (uint256) ;\n\n // function setLastUnpausedAt() internal;\n\n\n\n}\n" + }, + "contracts/interfaces/IProtocolFee.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IProtocolFee {\n function protocolFee() external view returns (uint16);\n}\n" + }, + "contracts/interfaces/IProtocolPausingManager.sol": { + "content": "\n\n\n\n\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\n//records the unpause timestamp s\ninterface IProtocolPausingManager {\n \n function isPauser(address _address) external view returns (bool);\n function protocolPaused() external view returns (bool);\n function liquidationsPaused() external view returns (bool);\n \n \n\n}\n" + }, + "contracts/interfaces/IReputationManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nenum RepMark {\n Good,\n Delinquent,\n Default\n}\n\ninterface IReputationManager {\n function initialize(address protocolAddress) external;\n\n function getDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory);\n\n function getDefaultedLoanIds(address _account)\n external\n returns (uint256[] memory);\n\n function getCurrentDelinquentLoanIds(address _account)\n external\n returns (uint256[] memory);\n\n function getCurrentDefaultLoanIds(address _account)\n external\n returns (uint256[] memory);\n\n function updateAccountReputation(address _account) external;\n\n function updateAccountReputation(address _account, uint256 _bidId)\n external\n returns (RepMark);\n}\n" + }, + "contracts/interfaces/ISmartCommitment.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nenum CommitmentCollateralType {\n NONE, // no collateral required\n ERC20,\n ERC721,\n ERC1155,\n ERC721_ANY_ID,\n ERC1155_ANY_ID,\n ERC721_MERKLE_PROOF,\n ERC1155_MERKLE_PROOF\n}\n\ninterface ISmartCommitment {\n function getPrincipalTokenAddress() external view returns (address);\n\n function getMarketId() external view returns (uint256);\n\n function getCollateralTokenAddress() external view returns (address);\n\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType);\n\n function getCollateralTokenId() external view returns (uint256);\n\n function getMinInterestRate(uint256 _delta) external view returns (uint16);\n\n function getMaxLoanDuration() external view returns (uint32);\n\n function getPrincipalAmountAvailableToBorrow()\n external\n view\n returns (uint256);\n\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount\n \n )\n external\n view\n returns (uint256);\n\n \n function acceptFundsForAcceptBid(\n address _borrower,\n uint256 _bidId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n address _collateralTokenAddress,\n uint256 _collateralTokenId,\n uint32 _loanDuration,\n uint16 _interestRate\n ) external;\n}\n" + }, + "contracts/interfaces/ISmartCommitmentForwarder.sol": { + "content": "\n\npragma solidity >=0.8.0 <0.9.0;\n\ninterface ISmartCommitmentForwarder {\n \n function acceptSmartCommitmentWithRecipient(\n address _smartCommitmentAddress,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration\n ) external returns (uint256 bidId) ;\n\n\n function setLiquidationProtocolFeePercent(uint256 _percent) \n external;\n\n function getLiquidationProtocolFeePercent() \n external view returns (uint256) ;\n\n\n\n}" + }, + "contracts/interfaces/ISwapRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ISwapRolloverLoan {\n struct RolloverCallbackArgs {\n address lenderCommitmentForwarder;\n uint256 loanId;\n address borrower;\n uint256 borrowerAmount;\n address rewardRecipient;\n uint256 rewardAmount;\n bytes acceptCommitmentArgs;\n }\n}\n" + }, + "contracts/interfaces/ITellerV2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport { Payment, BidState } from \"../TellerV2Storage.sol\";\nimport { Collateral } from \"./escrow/ICollateralEscrowV1.sol\";\n\ninterface ITellerV2 {\n /**\n * @notice Function for a borrower to create a bid for a loan.\n * @param _lendingToken The lending token asset requested to be borrowed.\n * @param _marketplaceId The unique id of the marketplace for the bid.\n * @param _principal The principal amount of the loan bid.\n * @param _duration The recurrent length of time before which a payment is due.\n * @param _APR The proposed interest rate for the loan bid.\n * @param _metadataURI The URI for additional borrower loan information as part of loan bid.\n * @param _receiver The address where the loan amount will be sent to.\n */\n function submitBid(\n address _lendingToken,\n uint256 _marketplaceId,\n uint256 _principal,\n uint32 _duration,\n uint16 _APR,\n string calldata _metadataURI,\n address _receiver\n ) external returns (uint256 bidId_);\n\n /**\n * @notice Function for a borrower to create a bid for a loan with Collateral.\n * @param _lendingToken The lending token asset requested to be borrowed.\n * @param _marketplaceId The unique id of the marketplace for the bid.\n * @param _principal The principal amount of the loan bid.\n * @param _duration The recurrent length of time before which a payment is due.\n * @param _APR The proposed interest rate for the loan bid.\n * @param _metadataURI The URI for additional borrower loan information as part of loan bid.\n * @param _receiver The address where the loan amount will be sent to.\n * @param _collateralInfo Additional information about the collateral asset.\n */\n function submitBid(\n address _lendingToken,\n uint256 _marketplaceId,\n uint256 _principal,\n uint32 _duration,\n uint16 _APR,\n string calldata _metadataURI,\n address _receiver,\n Collateral[] calldata _collateralInfo\n ) external returns (uint256 bidId_);\n\n /**\n * @notice Function for a lender to accept a proposed loan bid.\n * @param _bidId The id of the loan bid to accept.\n */\n function lenderAcceptBid(uint256 _bidId)\n external\n returns (\n uint256 amountToProtocol,\n uint256 amountToMarketplace,\n uint256 amountToBorrower\n );\n\n /**\n * @notice Function for users to make the minimum amount due for an active loan.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function repayLoanMinimum(uint256 _bidId) external;\n\n /**\n * @notice Function for users to repay an active loan in full.\n * @param _bidId The id of the loan to make the payment towards.\n */\n function repayLoanFull(uint256 _bidId) external;\n\n /**\n * @notice Function for users to make a payment towards an active loan.\n * @param _bidId The id of the loan to make the payment towards.\n * @param _amount The amount of the payment.\n */\n function repayLoan(uint256 _bidId, uint256 _amount) external;\n\n /**\n * @notice Checks to see if a borrower is delinquent.\n * @param _bidId The id of the loan bid to check for.\n */\n function isLoanDefaulted(uint256 _bidId) external view returns (bool);\n\n /**\n * @notice Checks to see if a loan was delinquent for longer than liquidation delay.\n * @param _bidId The id of the loan bid to check for.\n */\n function isLoanLiquidateable(uint256 _bidId) external view returns (bool);\n\n /**\n * @notice Checks to see if a borrower is delinquent.\n * @param _bidId The id of the loan bid to check for.\n */\n function isPaymentLate(uint256 _bidId) external view returns (bool);\n\n function getBidState(uint256 _bidId) external view returns (BidState);\n\n function getBorrowerActiveLoanIds(address _borrower)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @notice Returns the borrower address for a given bid.\n * @param _bidId The id of the bid/loan to get the borrower for.\n * @return borrower_ The address of the borrower associated with the bid.\n */\n function getLoanBorrower(uint256 _bidId)\n external\n view\n returns (address borrower_);\n\n /**\n * @notice Returns the lender address for a given bid.\n * @param _bidId The id of the bid/loan to get the lender for.\n * @return lender_ The address of the lender associated with the bid.\n */\n function getLoanLender(uint256 _bidId)\n external\n view\n returns (address lender_);\n\n function getLoanLendingToken(uint256 _bidId)\n external\n view\n returns (address token_);\n\n function getLoanMarketId(uint256 _bidId) external view returns (uint256);\n\n function getLoanSummary(uint256 _bidId)\n external\n view\n returns (\n address borrower,\n address lender,\n uint256 marketId,\n address principalTokenAddress,\n uint256 principalAmount,\n uint32 acceptedTimestamp,\n uint32 lastRepaidTimestamp,\n BidState bidState\n );\n\n function calculateAmountOwed(uint256 _bidId, uint256 _timestamp)\n external\n view\n returns (Payment memory owed);\n\n function calculateAmountDue(uint256 _bidId, uint256 _timestamp)\n external\n view\n returns (Payment memory due);\n\n function lenderCloseLoan(uint256 _bidId) external;\n\n function lenderCloseLoanWithRecipient(uint256 _bidId, address _recipient)\n external;\n\n function liquidateLoanFull(uint256 _bidId) external;\n\n function liquidateLoanFullWithRecipient(uint256 _bidId, address _recipient)\n external;\n\n function getLoanDefaultTimestamp(uint256 _bidId)\n external\n view\n returns (uint256);\n\n\n function getEscrowVault() external view returns(address);\n function getProtocolFeeRecipient () external view returns(address);\n\n\n // function isPauser(address _account) external view returns(bool);\n}\n" + }, + "contracts/interfaces/ITellerV2Context.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ITellerV2Context {\n function setTrustedMarketForwarder(uint256 _marketId, address _forwarder)\n external;\n\n function approveMarketForwarder(uint256 _marketId, address _forwarder)\n external;\n}\n" + }, + "contracts/interfaces/ITellerV2MarketForwarder.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\nimport { Collateral } from \"./escrow/ICollateralEscrowV1.sol\";\n\ninterface ITellerV2MarketForwarder {\n struct CreateLoanArgs {\n uint256 marketId;\n address lendingToken;\n uint256 principal;\n uint32 duration;\n uint16 interestRate;\n string metadataURI;\n address recipient;\n Collateral[] collateral;\n }\n}\n" + }, + "contracts/interfaces/ITellerV2Storage.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface ITellerV2Storage {\n function marketRegistry() external view returns (address);\n}\n" + }, + "contracts/interfaces/IUniswapPricingLibrary.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IUniswapPricingLibrary {\n \n\n struct PoolRouteConfig {\n address pool;\n bool zeroForOne;\n uint32 twapInterval;\n uint256 token0Decimals;\n uint256 token1Decimals;\n } \n\n\n\n function getUniswapPriceRatioForPoolRoutes(\n PoolRouteConfig[] memory poolRoutes\n ) external view returns (uint256 priceRatio);\n\n\n function getUniswapPriceRatioForPool(\n PoolRouteConfig memory poolRoute\n ) external view returns (uint256 priceRatio);\n\n}\n" + }, + "contracts/interfaces/oracleprotection/IHypernativeOracle.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IHypernativeOracle {\n function register(address account) external;\n function registerStrict(address account) external;\n function isBlacklistedAccount(address account) external view returns (bool);\n function isBlacklistedContext(address sender, address origin) external view returns (bool);\n function isTimeExceeded(address account) external view returns (bool);\n}" + }, + "contracts/interfaces/oracleprotection/IOracleProtectionManager.sol": { + "content": "// SPDX-Licence-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IOracleProtectionManager {\n\tfunction isOracleApproved(address _msgSender) external returns (bool) ;\n\t\t \n function isOracleApprovedAllowEOA(address _msgSender) external returns (bool);\n\n}" + }, + "contracts/interfaces/uniswap/IUniswapV3Factory.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\n/// @title The interface for the Uniswap V3 Factory\n/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees\ninterface IUniswapV3Factory {\n /// @notice Emitted when the owner of the factory is changed\n /// @param oldOwner The owner before the owner was changed\n /// @param newOwner The owner after the owner was changed\n event OwnerChanged(address indexed oldOwner, address indexed newOwner);\n\n /// @notice Emitted when a pool is created\n /// @param token0 The first token of the pool by address sort order\n /// @param token1 The second token of the pool by address sort order\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks\n /// @param pool The address of the created pool\n event PoolCreated(\n address indexed token0,\n address indexed token1,\n uint24 indexed fee,\n int24 tickSpacing,\n address pool\n );\n\n /// @notice Emitted when a new fee amount is enabled for pool creation via the factory\n /// @param fee The enabled fee, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee\n event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);\n\n /// @notice Returns the current owner of the factory\n /// @dev Can be changed by the current owner via setOwner\n /// @return The address of the factory owner\n function owner() external view returns (address);\n\n /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled\n /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context\n /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee\n /// @return The tick spacing\n function feeAmountTickSpacing(uint24 fee) external view returns (int24);\n\n /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist\n /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order\n /// @param tokenA The contract address of either token0 or token1\n /// @param tokenB The contract address of the other token\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @return pool The pool address\n function getPool(address tokenA, address tokenB, uint24 fee)\n external\n view\n returns (address pool);\n\n /// @notice Creates a pool for the given two tokens and fee\n /// @param tokenA One of the two tokens in the desired pool\n /// @param tokenB The other of the two tokens in the desired pool\n /// @param fee The desired fee for the pool\n /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved\n /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments\n /// are invalid.\n /// @return pool The address of the newly created pool\n function createPool(address tokenA, address tokenB, uint24 fee)\n external\n returns (address pool);\n\n /// @notice Updates the owner of the factory\n /// @dev Must be called by the current owner\n /// @param _owner The new owner of the factory\n function setOwner(address _owner) external;\n\n /// @notice Enables a fee amount with the given tickSpacing\n /// @dev Fee amounts may never be removed once enabled\n /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)\n /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount\n function enableFeeAmount(uint24 fee, int24 tickSpacing) external;\n}\n" + }, + "contracts/interfaces/uniswap/IUniswapV3Pool.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport \"./pool/IUniswapV3PoolImmutables.sol\";\nimport \"./pool/IUniswapV3PoolState.sol\";\nimport \"./pool/IUniswapV3PoolDerivedState.sol\";\nimport \"./pool/IUniswapV3PoolActions.sol\";\nimport \"./pool/IUniswapV3PoolOwnerActions.sol\";\nimport \"./pool/IUniswapV3PoolEvents.sol\";\n\n/// @title The interface for a Uniswap V3 Pool\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\n/// to the ERC20 specification\n/// @dev The pool interface is broken up into many smaller pieces\ninterface IUniswapV3Pool is\n IUniswapV3PoolImmutables,\n IUniswapV3PoolState,\n IUniswapV3PoolDerivedState,\n IUniswapV3PoolActions,\n IUniswapV3PoolOwnerActions,\n IUniswapV3PoolEvents\n{\n\n}\n" + }, + "contracts/interfaces/uniswap/pool/IUniswapV3PoolActions.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @notice Contains pool methods that can be called by anyone\ninterface IUniswapV3PoolActions {\n /// @notice Sets the initial price for the pool\n /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\n function initialize(uint160 sqrtPriceX96) external;\n\n /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\n /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\n /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n /// on tickLower, tickUpper, the amount of liquidity, and the current price.\n /// @param recipient The address for which the liquidity will be created\n /// @param tickLower The lower tick of the position in which to add liquidity\n /// @param tickUpper The upper tick of the position in which to add liquidity\n /// @param amount The amount of liquidity to mint\n /// @param data Any data that should be passed through to the callback\n /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n function mint(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount,\n bytes calldata data\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Collects tokens owed to a position\n /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n /// @param recipient The address which should receive the fees collected\n /// @param tickLower The lower tick of the position for which to collect fees\n /// @param tickUpper The upper tick of the position for which to collect fees\n /// @param amount0Requested How much token0 should be withdrawn from the fees owed\n /// @param amount1Requested How much token1 should be withdrawn from the fees owed\n /// @return amount0 The amount of fees collected in token0\n /// @return amount1 The amount of fees collected in token1\n function collect(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n\n /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n /// @dev Fees must be collected separately via a call to #collect\n /// @param tickLower The lower tick of the position for which to burn liquidity\n /// @param tickUpper The upper tick of the position for which to burn liquidity\n /// @param amount How much liquidity to burn\n /// @return amount0 The amount of token0 sent to the recipient\n /// @return amount1 The amount of token1 sent to the recipient\n function burn(int24 tickLower, int24 tickUpper, uint128 amount)\n external\n returns (uint256 amount0, uint256 amount1);\n\n /// @notice Swap token0 for token1, or token1 for token0\n /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\n /// @param recipient The address to receive the output of the swap\n /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\n /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\n /// @param data Any data to be passed through to the callback\n /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n function swap(\n address recipient,\n bool zeroForOne,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bytes calldata data\n ) external returns (int256 amount0, int256 amount1);\n\n /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\n /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\n /// with 0 amount{0,1} and sending the donation amount(s) from the callback\n /// @param recipient The address which will receive the token0 and token1 amounts\n /// @param amount0 The amount of token0 to send\n /// @param amount1 The amount of token1 to send\n /// @param data Any data to be passed through to the callback\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external;\n\n /// @notice Increase the maximum number of price and liquidity observations that this pool will store\n /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\n /// the input observationCardinalityNext.\n /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\n function increaseObservationCardinalityNext(\n uint16 observationCardinalityNext\n ) external;\n}\n" + }, + "contracts/interfaces/uniswap/pool/IUniswapV3PoolDerivedState.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that is not stored\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\n/// blockchain. The functions here may have variable gas costs.\ninterface IUniswapV3PoolDerivedState {\n /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n /// you must call it with secondsAgos = [3600, 0].\n /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\n /// timestamp\n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (\n int56[] memory tickCumulatives,\n uint160[] memory secondsPerLiquidityCumulativeX128s\n );\n\n /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\n /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\n /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\n /// snapshot is taken and the second snapshot is taken.\n /// @param tickLower The lower tick of the range\n /// @param tickUpper The upper tick of the range\n /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\n /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\n /// @return secondsInside The snapshot of seconds per liquidity for the range\n function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n external\n view\n returns (\n int56 tickCumulativeInside,\n uint160 secondsPerLiquidityInsideX128,\n uint32 secondsInside\n );\n}\n" + }, + "contracts/interfaces/uniswap/pool/IUniswapV3PoolEvents.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Events emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolEvents {\n /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\n /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\n /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\n /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\n event Initialize(uint160 sqrtPriceX96, int24 tick);\n\n /// @notice Emitted when liquidity is minted for a given position\n /// @param sender The address that minted the liquidity\n /// @param owner The owner of the position and recipient of any minted liquidity\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity minted to the position range\n /// @param amount0 How much token0 was required for the minted liquidity\n /// @param amount1 How much token1 was required for the minted liquidity\n event Mint(\n address sender,\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted when fees are collected by the owner of a position\n /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\n /// @param owner The owner of the position for which fees are collected\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount0 The amount of token0 fees collected\n /// @param amount1 The amount of token1 fees collected\n event Collect(\n address indexed owner,\n address recipient,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount0,\n uint128 amount1\n );\n\n /// @notice Emitted when a position's liquidity is removed\n /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\n /// @param owner The owner of the position for which liquidity is removed\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity to remove\n /// @param amount0 The amount of token0 withdrawn\n /// @param amount1 The amount of token1 withdrawn\n event Burn(\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted by the pool for any swaps between token0 and token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the output of the swap\n /// @param amount0 The delta of the token0 balance of the pool\n /// @param amount1 The delta of the token1 balance of the pool\n /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n /// @param liquidity The liquidity of the pool after the swap\n /// @param tick The log base 1.0001 of price of the pool after the swap\n event Swap(\n address indexed sender,\n address indexed recipient,\n int256 amount0,\n int256 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick\n );\n\n /// @notice Emitted by the pool for any flashes of token0/token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the tokens from flash\n /// @param amount0 The amount of token0 that was flashed\n /// @param amount1 The amount of token1 that was flashed\n /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\n /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\n event Flash(\n address indexed sender,\n address indexed recipient,\n uint256 amount0,\n uint256 amount1,\n uint256 paid0,\n uint256 paid1\n );\n\n /// @notice Emitted by the pool for increases to the number of observations that can be stored\n /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\n /// just before a mint/swap/burn.\n /// @param observationCardinalityNextOld The previous value of the next observation cardinality\n /// @param observationCardinalityNextNew The updated value of the next observation cardinality\n event IncreaseObservationCardinalityNext(\n uint16 observationCardinalityNextOld,\n uint16 observationCardinalityNextNew\n );\n\n /// @notice Emitted when the protocol fee is changed by the pool\n /// @param feeProtocol0Old The previous value of the token0 protocol fee\n /// @param feeProtocol1Old The previous value of the token1 protocol fee\n /// @param feeProtocol0New The updated value of the token0 protocol fee\n /// @param feeProtocol1New The updated value of the token1 protocol fee\n event SetFeeProtocol(\n uint8 feeProtocol0Old,\n uint8 feeProtocol1Old,\n uint8 feeProtocol0New,\n uint8 feeProtocol1New\n );\n\n /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\n /// @param sender The address that collects the protocol fees\n /// @param recipient The address that receives the collected protocol fees\n /// @param amount0 The amount of token0 protocol fees that is withdrawn\n /// @param amount0 The amount of token1 protocol fees that is withdrawn\n event CollectProtocol(\n address indexed sender,\n address indexed recipient,\n uint128 amount0,\n uint128 amount1\n );\n}\n" + }, + "contracts/interfaces/uniswap/pool/IUniswapV3PoolImmutables.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that never changes\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\ninterface IUniswapV3PoolImmutables {\n /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\n /// @return The contract address\n function factory() external view returns (address);\n\n /// @notice The first of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token0() external view returns (address);\n\n /// @notice The second of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token1() external view returns (address);\n\n /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\n /// @return The fee\n function fee() external view returns (uint24);\n\n /// @notice The pool tick spacing\n /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\n /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\n /// This value is an int24 to avoid casting even though it is always positive.\n /// @return The tick spacing\n function tickSpacing() external view returns (int24);\n\n /// @notice The maximum amount of position liquidity that can use any tick in the range\n /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\n /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\n /// @return The max amount of liquidity per tick\n function maxLiquidityPerTick() external view returns (uint128);\n}\n" + }, + "contracts/interfaces/uniswap/pool/IUniswapV3PoolOwnerActions.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissioned pool actions\n/// @notice Contains pool methods that may only be called by the factory owner\ninterface IUniswapV3PoolOwnerActions {\n /// @notice Set the denominator of the protocol's % share of the fees\n /// @param feeProtocol0 new protocol fee for token0 of the pool\n /// @param feeProtocol1 new protocol fee for token1 of the pool\n function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\n\n /// @notice Collect the protocol fee accrued to the pool\n /// @param recipient The address to which collected protocol fees should be sent\n /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\n /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\n /// @return amount0 The protocol fee collected in token0\n /// @return amount1 The protocol fee collected in token1\n function collectProtocol(\n address recipient,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n}\n" + }, + "contracts/interfaces/uniswap/pool/IUniswapV3PoolState.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\n/// per transaction\ninterface IUniswapV3PoolState {\n /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\n /// when accessed externally.\n /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\n /// tick The current tick of the pool, i.e. according to the last tick transition that was run.\n /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\n /// boundary.\n /// observationIndex The index of the last oracle observation that was written,\n /// observationCardinality The current maximum number of observations stored in the pool,\n /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n /// feeProtocol The protocol fee for both tokens of the pool.\n /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\n /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\n /// unlocked Whether the pool is currently locked to reentrancy\n function slot0()\n external\n view\n returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint16 observationIndex,\n uint16 observationCardinality,\n uint16 observationCardinalityNext,\n uint8 feeProtocol,\n bool unlocked\n );\n\n /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal0X128() external view returns (uint256);\n\n /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal1X128() external view returns (uint256);\n\n /// @notice The amounts of token0 and token1 that are owed to the protocol\n /// @dev Protocol fees will never exceed uint128 max in either token\n function protocolFees()\n external\n view\n returns (uint128 token0, uint128 token1);\n\n /// @notice The currently in range liquidity available to the pool\n /// @dev This value has no relationship to the total liquidity across all ticks\n function liquidity() external view returns (uint128);\n\n /// @notice Look up information about a specific tick in the pool\n /// @param tick The tick to look up\n /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\n /// tick upper,\n /// liquidityNet how much liquidity changes when the pool price crosses the tick,\n /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n /// secondsOutside the seconds spent on the other side of the tick from the current tick,\n /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\n /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\n /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\n /// a specific position.\n function ticks(int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128,\n int56 tickCumulativeOutside,\n uint160 secondsPerLiquidityOutsideX128,\n uint32 secondsOutside,\n bool initialized\n );\n\n /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\n function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n /// @notice Returns the information about a position by the position's key\n /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\n /// @return _liquidity The amount of liquidity in the position,\n /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\n function positions(bytes32 key)\n external\n view\n returns (\n uint128 _liquidity,\n uint256 feeGrowthInside0LastX128,\n uint256 feeGrowthInside1LastX128,\n uint128 tokensOwed0,\n uint128 tokensOwed1\n );\n\n /// @notice Returns data about a specific observation index\n /// @param index The element of the observations array to fetch\n /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\n /// ago, rather than at a specific index in the array.\n /// @return blockTimestamp The timestamp of the observation,\n /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n /// Returns initialized whether the observation has been initialized and the values are safe to use\n function observations(uint256 index)\n external\n view\n returns (\n uint32 blockTimestamp,\n int56 tickCumulative,\n uint160 secondsPerLiquidityCumulativeX128,\n bool initialized\n );\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/ExtensionsContextUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"../../interfaces/IExtensionsContext.sol\";\nimport \"@openzeppelin/contracts-upgradeable/metatx/ERC2771ContextUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\n\nabstract contract ExtensionsContextUpgradeable is IExtensionsContext {\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private userExtensions;\n\n event ExtensionAdded(address extension, address sender);\n event ExtensionRevoked(address extension, address sender);\n\n function hasExtension(address account, address extension)\n public\n view\n returns (bool)\n {\n return userExtensions[account][extension];\n }\n\n function addExtension(address extension) external {\n require(\n _msgSender() != extension,\n \"ExtensionsContextUpgradeable: cannot approve own extension\"\n );\n\n userExtensions[_msgSender()][extension] = true;\n emit ExtensionAdded(extension, _msgSender());\n }\n\n function revokeExtension(address extension) external {\n userExtensions[_msgSender()][extension] = false;\n emit ExtensionRevoked(extension, _msgSender());\n }\n\n function _msgSender() internal view virtual returns (address sender) {\n address sender;\n\n if (msg.data.length >= 20) {\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n\n if (hasExtension(sender, msg.sender)) {\n return sender;\n }\n }\n\n return msg.sender;\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" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroup_Smart.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n \n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\n\n// Interfaces\nimport \"../../../interfaces/ITellerV2Context.sol\";\nimport \"../../../interfaces/IProtocolFee.sol\";\n \nimport \"../../../interfaces/ITellerV2.sol\";\n\nimport \"../../../libraries/NumbersLib.sol\";\n\nimport \"../../../interfaces/uniswap/IUniswapV3Pool.sol\";\n\n\nimport \"../../../interfaces/IHasProtocolPausingManager.sol\";\n\nimport \"../../../interfaces/IProtocolPausingManager.sol\";\n\n\n\nimport \"../../../interfaces/uniswap/IUniswapV3Factory.sol\";\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\";\n\nimport \"../../../libraries/uniswap/TickMath.sol\";\nimport \"../../../libraries/uniswap/FixedPoint96.sol\";\nimport \"../../../libraries/uniswap/FullMath.sol\";\n\nimport {LenderCommitmentGroupShares} from \"./LenderCommitmentGroupShares.sol\";\n\n\nimport {OracleProtectedChild} from \"../../../oracleprotection/OracleProtectedChild.sol\";\n\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\nimport { CommitmentCollateralType, ISmartCommitment } from \"../../../interfaces/ISmartCommitment.sol\";\nimport { ILoanRepaymentListener } from \"../../../interfaces/ILoanRepaymentListener.sol\";\n\nimport { ILoanRepaymentCallbacks } from \"../../../interfaces/ILoanRepaymentCallbacks.sol\";\n\nimport { IEscrowVault } from \"../../../interfaces/IEscrowVault.sol\";\n\nimport { IPausableTimestamp } from \"../../../interfaces/IPausableTimestamp.sol\";\nimport { ILenderCommitmentGroup } from \"../../../interfaces/ILenderCommitmentGroup.sol\";\nimport { Payment } from \"../../../TellerV2Storage.sol\";\n\nimport {IUniswapPricingLibrary} from \"../../../interfaces/IUniswapPricingLibrary.sol\";\nimport {UniswapPricingLibraryV2} from \"../../../libraries/UniswapPricingLibraryV2.sol\";\n\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\n\n\n/*\n \n\n Each LenderCommitmentGroup SmartContract acts as its own Loan Commitment (for the SmartCommitmentForwarder) and acts as its own Lender in the Teller Protocol.\n\n Lender Users can deposit principal tokens in this contract and this will give them Share Tokens (LP tokens) representing their ownership in the liquidity pool of this contract.\n\n Borrower Users can borrow principal token funds from this contract (via the SCF contract) by providing collateral tokens in the proper amount as specified by the rules of this smart contract.\n These collateral tokens are then owned by this smart contract and are returned to the borrower via the Teller Protocol rules to the borrower if and only if the borrower repays principal and interest of the loan they took.\n\n If the borrower defaults on a loan, for 24 hours a liquidation auction is automatically conducted by this smart contract in order to incentivize a liquidator to take the collateral tokens in exchange for principal tokens.\n\n\n*/\n\ncontract LenderCommitmentGroup_Smart is\n ILenderCommitmentGroup,\n ISmartCommitment,\n ILoanRepaymentListener,\n IPausableTimestamp,\n Initializable,\n OracleProtectedChild,\n OwnableUpgradeable,\n PausableUpgradeable,\n ReentrancyGuardUpgradeable \n{\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n uint256 public immutable STANDARD_EXPANSION_FACTOR = 1e18;\n\n uint256 public immutable MIN_TWAP_INTERVAL = 3;\n\n uint256 public immutable UNISWAP_EXPANSION_FACTOR = 2**96;\n\n uint256 public immutable EXCHANGE_RATE_EXPANSION_FACTOR = 1e36; \n\n using SafeERC20 for IERC20;\n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable TELLER_V2;\n address public immutable SMART_COMMITMENT_FORWARDER;\n address public immutable UNISWAP_V3_FACTORY;\n \n \n LenderCommitmentGroupShares public poolSharesToken;\n\n IERC20 public principalToken;\n IERC20 public collateralToken;\n\n uint256 marketId;\n\n\n uint256 public totalPrincipalTokensCommitted; \n uint256 public totalPrincipalTokensWithdrawn;\n\n uint256 public totalPrincipalTokensLended;\n uint256 public totalPrincipalTokensRepaid; //subtract this and the above to find total principal tokens outstanding for loans\n uint256 public excessivePrincipalTokensRepaid;\n\n uint256 public totalInterestCollected;\n\n uint16 public liquidityThresholdPercent; //max ratio of principal allowed to be borrowed vs escrowed // maximum of 10000 (100%)\n uint16 public collateralRatio; //the overcollateralization ratio, typically >100 pct\n\n uint32 public maxLoanDuration;\n uint16 public interestRateLowerBound;\n uint16 public interestRateUpperBound;\n\n\n\n\n uint256 immutable public DEFAULT_WITHDRAW_DELAY_TIME_SECONDS = 300;\n uint256 immutable public MAX_WITHDRAW_DELAY_TIME = 86400;\n\n mapping(uint256 => bool) public activeBids;\n mapping(uint256 => uint256) public activeBidsAmountDueRemaining;\n\n int256 tokenDifferenceFromLiquidations;\n\n bool public firstDepositMade;\n uint256 public withdrawDelayTimeSeconds; \n\n IUniswapPricingLibrary.PoolRouteConfig[] public poolOracleRoutes;\n\n //configured by the owner. If 0 , not used. \n uint256 public maxPrincipalPerCollateralAmount; \n\n\n uint256 public lastUnpausedAt;\n \n\n event PoolInitialized(\n address indexed principalTokenAddress,\n address indexed collateralTokenAddress,\n uint256 marketId,\n uint32 maxLoanDuration,\n uint16 interestRateLowerBound,\n uint16 interestRateUpperBound,\n uint16 liquidityThresholdPercent,\n uint16 loanToValuePercent,\n address poolSharesToken\n );\n\n event LenderAddedPrincipal(\n address indexed lender,\n uint256 amount,\n uint256 sharesAmount,\n address indexed sharesRecipient\n );\n\n event BorrowerAcceptedFunds(\n address indexed borrower,\n uint256 indexed bidId,\n uint256 principalAmount,\n uint256 collateralAmount,\n uint32 loanDuration,\n uint16 interestRate\n );\n\n event EarningsWithdrawn(\n address indexed lender,\n uint256 amountPoolSharesTokens,\n uint256 principalTokensWithdrawn,\n address indexed recipient\n );\n\n\n event DefaultedLoanLiquidated(\n uint256 indexed bidId,\n address indexed liquidator,\n uint256 amountDue, \n int256 tokenAmountDifference \n );\n\n\n event LoanRepaid(\n uint256 indexed bidId,\n address indexed repayer,\n uint256 principalAmount,\n uint256 interestAmount,\n uint256 totalPrincipalRepaid,\n uint256 totalInterestCollected\n );\n\n\n event WithdrawFromEscrow(\n \n uint256 indexed amount\n\n );\n\n\n modifier onlySmartCommitmentForwarder() {\n require(\n msg.sender == address(SMART_COMMITMENT_FORWARDER),\n \"Can only be called by Smart Commitment Forwarder\"\n );\n _;\n }\n\n modifier onlyTellerV2() {\n require(\n msg.sender == address(TELLER_V2),\n \"Can only be called by TellerV2\"\n );\n _;\n }\n\n\n modifier onlyProtocolOwner() {\n require(\n msg.sender == Ownable(address(TELLER_V2)).owner(),\n \"Not Protocol Owner\"\n );\n _;\n }\n\n modifier onlyProtocolPauser() {\n\n address pausingManager = IHasProtocolPausingManager( address(TELLER_V2) ).getProtocolPausingManager();\n\n require(\n IProtocolPausingManager( pausingManager ).isPauser(msg.sender) ,\n \"Not Owner or Protocol Owner\"\n );\n _;\n }\n\n modifier bidIsActiveForGroup(uint256 _bidId) {\n require(activeBids[_bidId] == true, \"Bid is not active for group\");\n\n _;\n }\n \n\n modifier whenForwarderNotPaused() {\n require( PausableUpgradeable(address(SMART_COMMITMENT_FORWARDER)).paused() == false , \"Smart Commitment Forwarder is paused\");\n _;\n }\n\n\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder,\n address _uniswapV3Factory\n ) OracleProtectedChild(_smartCommitmentForwarder) {\n TELLER_V2 = _tellerV2;\n SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n UNISWAP_V3_FACTORY = _uniswapV3Factory;\n }\n\n /**\n * @notice Initializes the LenderCommitmentGroup_Smart contract.\n * @param _commitmentGroupConfig Configuration for the commitment group (lending pool).\n * @param _poolOracleRoutes Route configuration for the principal/collateral oracle.\n * @return poolSharesToken_ Address of the deployed pool shares token.\n */\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes\n ) external initializer returns (address poolSharesToken_) {\n \n __Ownable_init();\n __Pausable_init();\n\n principalToken = IERC20(_commitmentGroupConfig.principalTokenAddress);\n collateralToken = IERC20(_commitmentGroupConfig.collateralTokenAddress);\n \n marketId = _commitmentGroupConfig.marketId;\n\n withdrawDelayTimeSeconds = DEFAULT_WITHDRAW_DELAY_TIME_SECONDS;\n\n //in order for this to succeed, first, the SmartCommitmentForwarder needs to be a trusted forwarder for the market \n ITellerV2Context(TELLER_V2).approveMarketForwarder(\n _commitmentGroupConfig.marketId,\n SMART_COMMITMENT_FORWARDER\n );\n\n maxLoanDuration = _commitmentGroupConfig.maxLoanDuration;\n interestRateLowerBound = _commitmentGroupConfig.interestRateLowerBound;\n interestRateUpperBound = _commitmentGroupConfig.interestRateUpperBound;\n\n require(interestRateLowerBound <= interestRateUpperBound, \"invalid _interestRateLowerBound\");\n\n \n liquidityThresholdPercent = _commitmentGroupConfig.liquidityThresholdPercent;\n collateralRatio = _commitmentGroupConfig.collateralRatio;\n \n require( liquidityThresholdPercent <= 10000, \"invalid _liquidityThresholdPercent\"); \n\n for (uint256 i = 0; i < _poolOracleRoutes.length; i++) {\n poolOracleRoutes.push(_poolOracleRoutes[i]);\n }\n\n\n require(poolOracleRoutes.length >= 1 && poolOracleRoutes.length <= 2, \"invalid pool routes length\");\n \n poolSharesToken_ = _deployPoolSharesToken();\n\n\n emit PoolInitialized(\n _commitmentGroupConfig.principalTokenAddress,\n _commitmentGroupConfig.collateralTokenAddress,\n _commitmentGroupConfig.marketId,\n _commitmentGroupConfig.maxLoanDuration,\n _commitmentGroupConfig.interestRateLowerBound,\n _commitmentGroupConfig.interestRateUpperBound,\n _commitmentGroupConfig.liquidityThresholdPercent,\n _commitmentGroupConfig.collateralRatio,\n //_commitmentGroupConfig.uniswapPoolFee,\n //_commitmentGroupConfig.twapInterval,\n poolSharesToken_\n );\n }\n\n\n /**\n * @notice Sets the delay time for withdrawing funds. Only Protocol Owner.\n * @param _seconds Delay time in seconds.\n */\n function setWithdrawDelayTime(uint256 _seconds) \n external \n onlyProtocolOwner {\n require( _seconds < MAX_WITHDRAW_DELAY_TIME );\n\n withdrawDelayTimeSeconds = _seconds;\n }\n\n\n /**\n * @notice Sets an optional manual ratio for principal/collateral ratio for borrowers. Only Pool Owner.\n * @param _maxPrincipalPerCollateralAmount Price ratio, expanded to support sub-one ratios.\n */\n function setMaxPrincipalPerCollateralAmount(uint256 _maxPrincipalPerCollateralAmount) \n external \n onlyOwner {\n maxPrincipalPerCollateralAmount = _maxPrincipalPerCollateralAmount;\n }\n\n /**\n * @notice Deploys the pool shares token for the lending pool.\n * @dev This function can only be called during initialization.\n * @return poolSharesToken_ Address of the deployed pool shares token.\n */\n function _deployPoolSharesToken()\n internal\n onlyInitializing\n returns (address poolSharesToken_)\n { \n require(\n address(poolSharesToken) == address(0),\n \"Pool shares already deployed\"\n );\n \n poolSharesToken = new LenderCommitmentGroupShares(\n \"LenderGroupShares\",\n \"SHR\",\n 18 \n );\n\n return address(poolSharesToken);\n } \n\n\n /**\n * @notice This determines the number of shares you get for depositing principal tokens and the number of principal tokens you receive for burning shares\n * @return rate_ The current exchange rate, scaled by the EXCHANGE_RATE_FACTOR.\n */\n\n function sharesExchangeRate() public view virtual returns (uint256 rate_) {\n \n\n uint256 poolTotalEstimatedValue = getPoolTotalEstimatedValue();\n\n if (poolSharesToken.totalSupply() == 0) {\n return EXCHANGE_RATE_EXPANSION_FACTOR; // 1 to 1 for first swap\n }\n\n rate_ =\n MathUpgradeable.mulDiv(poolTotalEstimatedValue , \n EXCHANGE_RATE_EXPANSION_FACTOR ,\n poolSharesToken.totalSupply() );\n }\n\n function sharesExchangeRateInverse()\n public\n view\n virtual\n returns (uint256 rate_)\n {\n return\n (EXCHANGE_RATE_EXPANSION_FACTOR * EXCHANGE_RATE_EXPANSION_FACTOR) /\n sharesExchangeRate();\n }\n\n function getPoolTotalEstimatedValue()\n public\n view\n returns (uint256 poolTotalEstimatedValue_)\n {\n \n int256 poolTotalEstimatedValueSigned = int256(totalPrincipalTokensCommitted) \n \n + int256(totalInterestCollected) + int256(tokenDifferenceFromLiquidations) \n + int256( excessivePrincipalTokensRepaid )\n - int256( totalPrincipalTokensWithdrawn )\n \n ;\n\n\n\n //if the poolTotalEstimatedValue_ is less than 0, we treat it as 0. \n poolTotalEstimatedValue_ = poolTotalEstimatedValueSigned > int256(0)\n ? uint256(poolTotalEstimatedValueSigned)\n : 0;\n }\n\n /**\n * @notice Adds principal to the lending pool in exchange for shares.\n * @param _amount Amount of principal tokens to deposit.\n * @param _sharesRecipient Address receiving the shares.\n * @param _minSharesAmountOut Minimum amount of shares expected.\n * @return sharesAmount_ Amount of shares minted.\n */\n function addPrincipalToCommitmentGroup(\n uint256 _amount,\n address _sharesRecipient,\n uint256 _minSharesAmountOut\n ) external whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n returns (uint256 sharesAmount_) {\n \n uint256 principalTokenBalanceBefore = principalToken.balanceOf(address(this));\n\n principalToken.safeTransferFrom(msg.sender, address(this), _amount);\n \n uint256 principalTokenBalanceAfter = principalToken.balanceOf(address(this));\n \n require( principalTokenBalanceAfter == principalTokenBalanceBefore + _amount, \"Token balance was not added properly\" );\n\n sharesAmount_ = _valueOfUnderlying(_amount, sharesExchangeRate());\n \n totalPrincipalTokensCommitted += _amount;\n \n //mint shares equal to _amount and give them to the shares recipient \n poolSharesToken.mint(_sharesRecipient, sharesAmount_);\n \n emit LenderAddedPrincipal( \n\n msg.sender,\n _amount,\n sharesAmount_,\n _sharesRecipient\n\n );\n\n require( sharesAmount_ >= _minSharesAmountOut, \"Invalid: Min Shares AmountOut\" );\n \n if(!firstDepositMade){\n require(msg.sender == owner(), \"Owner must initialize the pool with a deposit first.\");\n require( sharesAmount_>= 1e6, \"Initial shares amount must be atleast 1e6\" );\n\n firstDepositMade = true;\n }\n }\n\n function _valueOfUnderlying(uint256 amount, uint256 rate)\n internal\n pure\n returns (uint256 value_)\n {\n if (rate == 0) {\n return 0;\n }\n\n value_ = MathUpgradeable.mulDiv(amount , EXCHANGE_RATE_EXPANSION_FACTOR , rate );\n }\n\n /**\n * @notice Validates loan parameters and starts the TellerV2 Loan where this contract as the lender.\n * @dev Must be called via the Smart Commitment Forwarder \n * @param _borrower Address of the borrower accepting the loan.\n * @param _bidId Identifier for the loan bid.\n * @param _principalAmount Amount of principal being lent.\n * @param _collateralAmount Amount of collateral provided by the borrower.\n * @param _collateralTokenAddress Address of the collateral token contract.\n * @param _collateralTokenId Token ID of the collateral (if applicable).\n * @param _loanDuration Duration of the loan in seconds.\n * @param _interestRate Interest rate for the loan, scaled by 100 (e.g., 500 = 5%).\n */\n function acceptFundsForAcceptBid(\n address _borrower,\n uint256 _bidId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n address _collateralTokenAddress,\n uint256 _collateralTokenId, \n uint32 _loanDuration,\n uint16 _interestRate\n ) external onlySmartCommitmentForwarder whenForwarderNotPaused whenNotPaused {\n \n require(\n _collateralTokenAddress == address(collateralToken),\n \"Mismatching collateral token\"\n );\n //the interest rate must be at least as high has the commitment demands. The borrower can use a higher interest rate although that would not be beneficial to the borrower.\n require(_interestRate >= getMinInterestRate(_principalAmount), \"Invalid interest rate\");\n //the loan duration must be less than the commitment max loan duration. The lender who made the commitment expects the money to be returned before this window.\n require(_loanDuration <= maxLoanDuration, \"Invalid loan max duration\");\n\n require(\n getPrincipalAmountAvailableToBorrow() >= _principalAmount,\n \"Invalid loan max principal\"\n );\n \n \n uint256 requiredCollateral = calculateCollateralRequiredToBorrowPrincipal(\n _principalAmount\n );\n\n\n\n require( \n _collateralAmount >=\n requiredCollateral,\n \"Insufficient Borrower Collateral\"\n );\n \n principalToken.safeApprove(address(TELLER_V2), _principalAmount);\n\n //do not have to override msg.sender here as this contract is the lender !\n _acceptBidWithRepaymentListener(_bidId);\n\n totalPrincipalTokensLended += _principalAmount;\n\n activeBids[_bidId] = true; //bool for now\n activeBidsAmountDueRemaining[_bidId] = _principalAmount;\n \n\n emit BorrowerAcceptedFunds( \n _borrower,\n _bidId,\n _principalAmount,\n _collateralAmount, \n _loanDuration,\n _interestRate \n );\n }\n\n /**\n * @notice Internal function to accept a loan bid and set a repayment listener.\n * @dev Interacts with the Teller Protocol to accept the bid and register the repayment listener.\n * @param _bidId Identifier for the loan bid being accepted.\n */\n function _acceptBidWithRepaymentListener(uint256 _bidId) internal {\n ITellerV2(TELLER_V2).lenderAcceptBid(_bidId); //this gives out the funds to the borrower\n\n ILoanRepaymentCallbacks(TELLER_V2).setRepaymentListenerForBid(\n _bidId,\n address(this)\n );\n\n \n }\n\n \n function prepareSharesForBurn(\n uint256 _amountPoolSharesTokens \n ) external whenForwarderNotPaused whenNotPaused nonReentrant\n returns (bool) {\n \n return poolSharesToken.prepareSharesForBurn(msg.sender, _amountPoolSharesTokens); \n }\n\n\n\n\n /**\n * @notice Burns shares to withdraw an equivalent amount of principal tokens.\n * @dev Requires shares to have been prepared for withdrawal in advance.\n * @param _amountPoolSharesTokens Amount of pool shares to burn.\n * @param _recipient Address receiving the withdrawn principal tokens.\n * @param _minAmountOut Minimum amount of principal tokens expected to be withdrawn.\n * @return principalTokenValueToWithdraw Amount of principal tokens withdrawn.\n */\n function burnSharesToWithdrawEarnings(\n uint256 _amountPoolSharesTokens,\n address _recipient,\n uint256 _minAmountOut\n ) external whenForwarderNotPaused whenNotPaused nonReentrant onlyOracleApprovedAllowEOA \n returns (uint256) {\n \n \n \n //this should compute BEFORE shares burn \n uint256 principalTokenValueToWithdraw = _valueOfUnderlying(\n _amountPoolSharesTokens,\n sharesExchangeRateInverse()\n );\n\n poolSharesToken.burn(msg.sender, _amountPoolSharesTokens, withdrawDelayTimeSeconds);\n\n totalPrincipalTokensWithdrawn += principalTokenValueToWithdraw;\n\n principalToken.safeTransfer(_recipient, principalTokenValueToWithdraw);\n\n\n emit EarningsWithdrawn(\n msg.sender,\n _amountPoolSharesTokens,\n principalTokenValueToWithdraw,\n _recipient\n );\n \n require( principalTokenValueToWithdraw >= _minAmountOut ,\"Invalid: Min Amount Out\");\n\n return principalTokenValueToWithdraw;\n }\n\n/**\n * @notice Liquidates a defaulted loan using a reverse auction that starts high and falls to zero.\n * @dev The amount of tokens withdrawn from the liquidator is always the sum of _tokenAmountDifference + amountDue .\n * @dev Handles the liquidation process for a defaulted loan bid, ensuring all conditions for liquidation are met.\n * @param _bidId Identifier for the defaulted loan bid.\n * @param _tokenAmountDifference The incentive difference in tokens required for liquidation. Positive values indicate extra tokens to take, and negative values indicate extra tokens to give.\n */\n\n\n function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external whenForwarderNotPaused whenNotPaused bidIsActiveForGroup(_bidId) nonReentrant onlyOracleApprovedAllowEOA {\n \n\n\n uint256 loanTotalPrincipalAmount = _getLoanTotalPrincipalAmount(_bidId); //only used for the auction delta amount \n \n (uint256 principalDue,uint256 interestDue) = _getAmountOwedForBid(_bidId); //this is the base amount that must be repaid by the liquidator\n \n\n uint256 loanDefaultedTimeStamp = ITellerV2(TELLER_V2)\n .getLoanDefaultTimestamp(_bidId);\n\n uint256 loanDefaultedOrUnpausedAtTimeStamp = Math.max(\n loanDefaultedTimeStamp,\n getLastUnpausedAt()\n );\n\n int256 minAmountDifference = getMinimumAmountDifferenceToCloseDefaultedLoan(\n loanTotalPrincipalAmount,\n loanDefaultedOrUnpausedAtTimeStamp\n );\n \n \n require(\n _tokenAmountDifference >= minAmountDifference,\n \"Insufficient tokenAmountDifference\"\n );\n\n\n if (minAmountDifference > 0) {\n //this is used when the collateral value is higher than the principal (rare)\n //the loan will be completely made whole and our contract gets extra funds too\n uint256 tokensToTakeFromSender = abs(minAmountDifference);\n \n \n \n uint256 liquidationProtocolFee = Math.mulDiv( \n tokensToTakeFromSender , \n ISmartCommitmentForwarder(SMART_COMMITMENT_FORWARDER)\n .getLiquidationProtocolFeePercent(),\n 10000) ;\n \n\n IERC20(principalToken).safeTransferFrom(\n msg.sender,\n address(this),\n principalDue + tokensToTakeFromSender - liquidationProtocolFee\n ); \n \n address protocolFeeRecipient = ITellerV2(address(TELLER_V2)).getProtocolFeeRecipient();\n\n if (liquidationProtocolFee > 0) {\n IERC20(principalToken).safeTransferFrom(\n msg.sender,\n address(protocolFeeRecipient),\n liquidationProtocolFee\n );\n }\n\n totalPrincipalTokensRepaid += principalDue;\n\n \n tokenDifferenceFromLiquidations += int256(tokensToTakeFromSender - liquidationProtocolFee );\n\n\n } else {\n \n \n uint256 tokensToGiveToSender = abs(minAmountDifference);\n\n \n \n //dont stipend/refund more than principalDue base \n if (tokensToGiveToSender > principalDue) {\n tokensToGiveToSender = principalDue;\n }\n\n uint256 netAmountDue = principalDue - tokensToGiveToSender ;\n \n\n if (netAmountDue > 0) {\n IERC20(principalToken).safeTransferFrom(\n msg.sender,\n address(this),\n netAmountDue //principalDue - tokensToGiveToSender \n );\n }\n\n totalPrincipalTokensRepaid += principalDue;\n\n tokenDifferenceFromLiquidations -= int256(tokensToGiveToSender);\n \n\n \n }\n\n //this will effectively 'forfeit' tokens from this contract equal to the amount (principal) that has not been repaid ! principalDue\n //this will give collateral to the caller\n ITellerV2(TELLER_V2).lenderCloseLoanWithRecipient(_bidId, msg.sender);\n \n \n emit DefaultedLoanLiquidated(\n _bidId,\n msg.sender,\n principalDue, \n _tokenAmountDifference\n );\n }\n\n \n\n function getLastUnpausedAt() \n public view \n returns (uint256) {\n\n\n return Math.max(\n lastUnpausedAt,\n IPausableTimestamp(SMART_COMMITMENT_FORWARDER).getLastUnpausedAt() //this counts tellerV2 pausing\n )\n ;\n \n\n }\n\n\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n function _getLoanTotalPrincipalAmount(uint256 _bidId )\n internal\n view\n virtual\n returns (uint256 principalAmount)\n {\n (,,,, principalAmount, , , )\n = ITellerV2(TELLER_V2).getLoanSummary(_bidId);\n\n \n }\n\n \n\n function _getAmountOwedForBid(uint256 _bidId )\n internal\n view\n virtual\n returns (uint256 principal,uint256 interest)\n {\n Payment memory owed = ITellerV2(TELLER_V2).calculateAmountOwed(_bidId, block.timestamp );\n\n return (owed.principal, owed.interest) ;\n }\n\n\n function getTokenDifferenceFromLiquidations() public view returns (int256){\n\n return tokenDifferenceFromLiquidations;\n\n }\n \n\n /*\n * @dev This function will calculate the incentive amount (using a uniswap bonus plus a timer)\n of principal tokens that will be given to incentivize liquidating a loan \n\n * @dev As time approaches infinite, the output approaches -1 * AmountDue . \n */\n function getMinimumAmountDifferenceToCloseDefaultedLoan(\n uint256 _amountOwed,\n uint256 _loanDefaultedTimestamp\n ) public view virtual returns (int256 amountDifference_) {\n require(\n _loanDefaultedTimestamp > 0,\n \"Loan defaulted timestamp must be greater than zero\"\n );\n require(\n block.timestamp > _loanDefaultedTimestamp,\n \"Loan defaulted timestamp must be in the past\"\n );\n\n uint256 secondsSinceDefaulted = block.timestamp -\n _loanDefaultedTimestamp;\n\n //this starts at 764% and falls to -100% \n int256 incentiveMultiplier = int256(86400 - 10000) -\n int256(secondsSinceDefaulted);\n\n if (incentiveMultiplier < -10000) {\n incentiveMultiplier = -10000;\n }\n\n amountDifference_ =\n (int256(_amountOwed) * incentiveMultiplier) /\n int256(10000);\n }\n\n function abs(int x) private pure returns (uint) {\n return x >= 0 ? uint(x) : uint(-x);\n }\n\n\n function calculateCollateralRequiredToBorrowPrincipal( \n uint256 _principalAmount\n ) public\n view\n virtual\n returns (uint256) {\n\n uint256 baseAmount = calculateCollateralTokensAmountEquivalentToPrincipalTokens(\n _principalAmount\n ); \n\n //this is an amount of collateral\n return baseAmount.percent(collateralRatio);\n }\n\n /* \n * @dev this is expanded by 10e18\n * @dev this logic is very similar to that used in LCFA \n */\n function calculateCollateralTokensAmountEquivalentToPrincipalTokens(\n uint256 principalAmount \n ) public view virtual returns (uint256 collateralTokensAmountToMatchValue) {\n \n uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2\n .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes);\n \n \n uint256 principalPerCollateralAmount = maxPrincipalPerCollateralAmount == 0 \n ? pairPriceWithTwapFromOracle \n : Math.min(\n pairPriceWithTwapFromOracle,\n maxPrincipalPerCollateralAmount //this is expanded by uniswap exp factor \n );\n\n\n return\n getRequiredCollateral(\n principalAmount,\n principalPerCollateralAmount \n );\n }\n\n\n function getUniswapPriceRatioForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) external view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2\n .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes);\n \n\n return pairPriceWithTwapFromOracle;\n }\n\n function getPrincipalForCollateralForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolOracleRoutes\n ) external view virtual returns (uint256 ) {\n \n uint256 pairPriceWithTwapFromOracle = UniswapPricingLibraryV2\n .getUniswapPriceRatioForPoolRoutes(poolOracleRoutes);\n \n \n uint256 principalPerCollateralAmount = maxPrincipalPerCollateralAmount == 0 \n ? pairPriceWithTwapFromOracle \n : Math.min(\n pairPriceWithTwapFromOracle,\n maxPrincipalPerCollateralAmount //this is expanded by uniswap exp factor \n );\n\n\n return principalPerCollateralAmount;\n }\n\n\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount \n \n ) public view virtual returns (uint256) {\n \n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n STANDARD_EXPANSION_FACTOR,\n _maxPrincipalPerCollateralAmount,\n MathUpgradeable.Rounding.Up\n ); \n }\n \n\n /*\n @dev This callback occurs when a TellerV2 repayment happens or when a TellerV2 liquidate happens \n @dev lenderCloseLoan does not trigger a repayLoanCallback \n @dev It is important that only teller loans for this specific pool can call this\n @dev It is important that this function does not revert even if paused since repayments can occur in this case\n */\n function repayLoanCallback(\n uint256 _bidId,\n address repayer,\n uint256 principalAmount,\n uint256 interestAmount\n ) external onlyTellerV2 bidIsActiveForGroup(_bidId) { \n\n uint256 amountDueRemaining = activeBidsAmountDueRemaining[_bidId];\n\n \n uint256 principalAmountAppliedToAmountDueRemaining = principalAmount < amountDueRemaining ? \n principalAmount : amountDueRemaining; \n\n\n //should never fail due to the above .\n activeBidsAmountDueRemaining[_bidId] -= principalAmountAppliedToAmountDueRemaining; \n \n\n totalPrincipalTokensRepaid += principalAmountAppliedToAmountDueRemaining;\n totalInterestCollected += interestAmount;\n\n\n uint256 excessiveRepaymentAmount = principalAmount < amountDueRemaining ? \n 0 : (principalAmount - amountDueRemaining); \n \n excessivePrincipalTokensRepaid += excessiveRepaymentAmount; \n\n\n emit LoanRepaid(\n _bidId,\n repayer,\n principalAmount,\n interestAmount,\n totalPrincipalTokensRepaid,\n totalInterestCollected\n );\n }\n\n\n /*\n If principal get stuck in the escrow vault for any reason, anyone may\n call this function to move them from that vault in to this contract \n\n @dev there is no need to increment totalPrincipalTokensRepaid here as that is accomplished by the repayLoanCallback\n */\n function withdrawFromEscrowVault ( uint256 _amount ) external whenForwarderNotPaused whenNotPaused {\n\n address _escrowVault = ITellerV2(TELLER_V2).getEscrowVault();\n\n IEscrowVault(_escrowVault).withdraw(address(principalToken), _amount ); \n\n emit WithdrawFromEscrow(_amount);\n\n }\n \n \n function getTotalPrincipalTokensOutstandingInActiveLoans()\n public\n view\n returns (uint256)\n { \n if (totalPrincipalTokensRepaid > totalPrincipalTokensLended) {\n return 0;\n }\n\n return totalPrincipalTokensLended - totalPrincipalTokensRepaid;\n }\n\n\n\n\n function getCollateralTokenAddress() external view returns (address) {\n return address(collateralToken);\n }\n\n function getCollateralTokenId() external view returns (uint256) {\n return 0;\n }\n\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType)\n {\n return CommitmentCollateralType.ERC20;\n }\n \n\n function getMarketId() external view returns (uint256) {\n return marketId;\n }\n\n function getMaxLoanDuration() external view returns (uint32) {\n return maxLoanDuration;\n }\n\n\n function getPoolUtilizationRatio(uint256 activeLoansAmountDelta ) public view returns (uint16) {\n\n if (getPoolTotalEstimatedValue() == 0) {\n return 0;\n }\n\n return uint16( Math.min( \n MathUpgradeable.mulDiv( \n (getTotalPrincipalTokensOutstandingInActiveLoans() + activeLoansAmountDelta), \n 10000 ,\n getPoolTotalEstimatedValue() ) , \n 10000 ));\n\n }\n\n function getMinInterestRate(uint256 amountDelta) public view returns (uint16) {\n return interestRateLowerBound + \n uint16( uint256(interestRateUpperBound-interestRateLowerBound)\n .percent(getPoolUtilizationRatio(amountDelta )\n \n ) );\n } \n \n\n function getPrincipalTokenAddress() external view returns (address) {\n return address(principalToken);\n }\n\n \n\n function getPrincipalAmountAvailableToBorrow()\n public\n view\n returns (uint256)\n { \n\n return ( uint256( getPoolTotalEstimatedValue() )).percent(liquidityThresholdPercent) -\n getTotalPrincipalTokensOutstandingInActiveLoans();\n \n }\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pauseLendingPool() public virtual onlyProtocolPauser whenNotPaused {\n _pause();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol undo a previously implemented emergency stop.\n */\n function unpauseLendingPool() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/LenderCommitmentGroup/LenderCommitmentGroupShares.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\n \n\ncontract LenderCommitmentGroupShares is ERC20, Ownable {\n uint8 private immutable DECIMALS;\n\n\n mapping(address => uint256) public poolSharesPreparedToWithdrawForLender;\n mapping(address => uint256) public poolSharesPreparedTimestamp;\n\n\n event SharesPrepared(\n address recipient,\n uint256 sharesAmount,\n uint256 preparedAt\n\n );\n\n\n\n constructor(string memory _name, string memory _symbol, uint8 _decimals)\n ERC20(_name, _symbol)\n Ownable()\n {\n DECIMALS = _decimals;\n }\n\n function mint(address _recipient, uint256 _amount) external onlyOwner {\n _mint(_recipient, _amount);\n }\n\n function burn(address _burner, uint256 _amount, uint256 withdrawDelayTimeSeconds) external onlyOwner {\n\n\n //require prepared \n require(poolSharesPreparedToWithdrawForLender[_burner] >= _amount,\"Shares not prepared for withdraw\");\n require(poolSharesPreparedTimestamp[_burner] <= block.timestamp - withdrawDelayTimeSeconds,\"Shares not prepared for withdraw\");\n \n \n //reset prepared \n poolSharesPreparedToWithdrawForLender[_burner] = 0;\n poolSharesPreparedTimestamp[_burner] = block.timestamp;\n \n\n _burn(_burner, _amount);\n }\n\n function decimals() public view virtual override returns (uint8) {\n return DECIMALS;\n }\n\n\n // ---- \n\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal override {\n\n if (amount > 0) {\n //reset prepared \n poolSharesPreparedToWithdrawForLender[from] = 0;\n poolSharesPreparedTimestamp[from] = block.timestamp;\n\n }\n\n \n }\n\n\n // ---- \n\n\n /**\n * @notice Prepares shares for withdrawal, allowing the user to burn them later for principal tokens + accrued interest.\n * @param _amountPoolSharesTokens Amount of pool shares to prepare for withdrawal.\n * @return True if the preparation is successful.\n */\n function prepareSharesForBurn(\n address _recipient,\n uint256 _amountPoolSharesTokens \n ) external onlyOwner\n returns (bool) {\n \n return _prepareSharesForBurn(_recipient, _amountPoolSharesTokens); \n }\n\n\n /**\n * @notice Internal function to prepare shares for withdrawal using the required delay to mitigate sandwich attacks.\n * @param _recipient Address of the user preparing their shares.\n * @param _amountPoolSharesTokens Amount of pool shares to prepare for withdrawal.\n * @return True if the preparation is successful.\n */\n\n function _prepareSharesForBurn(\n address _recipient,\n uint256 _amountPoolSharesTokens \n ) internal returns (bool) {\n \n require( balanceOf(_recipient) >= _amountPoolSharesTokens );\n\n poolSharesPreparedToWithdrawForLender[_recipient] = _amountPoolSharesTokens; \n poolSharesPreparedTimestamp[_recipient] = block.timestamp; \n\n\n emit SharesPrepared( \n _recipient,\n _amountPoolSharesTokens,\n block.timestamp\n\n );\n\n return true; \n }\n\n\n\n\n\n\n\n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/SwapRolloverLoan_G1.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n// Interfaces\nimport \"../../../interfaces/ITellerV2.sol\";\nimport \"../../../interfaces/IProtocolFee.sol\";\nimport \"../../../interfaces/ITellerV2Storage.sol\";\nimport \"../../../interfaces/IMarketRegistry.sol\";\nimport \"../../../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"../../../interfaces/ISmartCommitmentForwarder.sol\";\nimport \"../../../interfaces/ISwapRolloverLoan.sol\";\nimport \"../../../libraries/NumbersLib.sol\";\n\n \nimport '../../../libraries/uniswap/periphery/base/PeripheryPayments.sol';\nimport '../../../libraries/uniswap/periphery/base/PeripheryImmutableState.sol';\nimport '../../../libraries/uniswap/periphery/libraries/PoolAddress.sol';\nimport '../../../libraries/uniswap/periphery/libraries/CallbackValidation.sol';\nimport '../../../libraries/uniswap/periphery/libraries/TransferHelper.sol';\nimport '../../../libraries/uniswap/periphery/interfaces/ISwapRouter.sol';\n\nimport '../../../libraries/uniswap/core/interfaces/IUniswapV3Factory.sol';\n\nimport '../../../libraries/uniswap/core/libraries/LowGasSafeMath.sol';\n\nimport '../../../libraries/uniswap/core/interfaces/callback/IUniswapV3FlashCallback.sol';\n \n \n\n\ncontract SwapRolloverLoan_G1 is IUniswapV3FlashCallback, PeripheryPayments {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n\n using LowGasSafeMath for uint256;\n using LowGasSafeMath for int256;\n\n \n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n ITellerV2 public immutable TELLER_V2;\n \n \n\n event RolloverLoanComplete(\n address borrower,\n uint256 originalLoanId,\n uint256 newLoanId,\n uint256 fundsRemaining\n );\n\n event RolloverWithReferral(\n \n uint256 newLoanId,\n address flashToken,\n\n address rewardRecipient,\n uint256 rewardAmount,\n uint256 atmId\n );\n\n \n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n address smartCommitmentAddress; //if this is not address(0), we will use this ! leave empty if not used. \n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n bytes32[] merkleProof; //empty array if not used\n }\n\n struct FlashSwapArgs {\n\n address token0;\n address token1;\n uint24 fee;\n \n\n uint256 flashAmount;\n bool borrowToken1; // if false, borrow token 0 \n \n \n\n } \n\n struct RolloverCallbackArgs {\n address lenderCommitmentForwarder;\n uint256 loanId;\n address borrower;\n uint256 borrowerAmount;\n uint256 atmId; \n address rewardRecipient;\n uint256 rewardAmount;\n bytes acceptCommitmentArgs;\n bytes flashSwapArgs;\n }\n\n\n /**\n *\n * @notice Initializes the FlashRolloverLoan with necessary contract addresses.\n *\n * @dev Using a custom OpenZeppelin upgrades tag. Ensure the constructor logic is safe for upgrades.\n *\n * @param _tellerV2 The address of the TellerV2 contract.\n * @param _factory The address of the UniswapV3 Factory contract to help with callback validation.\n * @param _WETH9 The address of the WETH Contract as this is instrumental to core uniswap logic.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2, \n address _factory,\n address _WETH9\n ) PeripheryImmutableState(_factory, _WETH9) {\n TELLER_V2 = ITellerV2(_tellerV2);\n \n }\n \n\n\n\n /**\n *\n * @notice Allows the borrower to rollover their existing loan using a flash loan mechanism.\n * The borrower might also provide an additional amount during the rollover.\n *\n * @dev The function first verifies that the caller is the borrower of the loan.\n * It then optionally transfers the additional amount specified by the borrower.\n * A flash loan is then taken from the pool to facilitate the rollover and\n * a callback is executed for further operations.\n *\n * @param _loanId Identifier of the existing loan to be rolled over.\n \n * @param _borrowerAmount Additional amount that the borrower may want to add during rollover.\n * @param _acceptCommitmentArgs Commitment arguments that might be necessary for internal operations.\n * \n */\n function rolloverLoanWithFlashSwap(\n address _lenderCommitmentForwarder,\n uint256 _loanId, \n\n uint256 _borrowerAmount, //an additional amount borrower may have to add \n\n FlashSwapArgs calldata _flashSwapArgs, \n\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"Must be borrower\");\n\n\n {\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n \n if (_borrowerAmount > 0) {\n TransferHelper.safeTransferFrom(lendingToken, borrower, address(this), _borrowerAmount); \n }\n }\n\n \n IUniswapV3Pool( \n getUniswapPoolAddress (\n _flashSwapArgs.token0,\n _flashSwapArgs.token1,\n _flashSwapArgs.fee\n )\n ).flash( \n address(this),\n _flashSwapArgs.borrowToken1 ? 0 : _flashSwapArgs.flashAmount, \n _flashSwapArgs.borrowToken1 ? _flashSwapArgs.flashAmount : 0, \n abi.encode( \n RolloverCallbackArgs({\n lenderCommitmentForwarder : _lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount, \n rewardRecipient: address(0),\n rewardAmount: 0,\n atmId: 0, \n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs),\n\n flashSwapArgs: abi.encode( _flashSwapArgs) \n \n })\n\n )\n );\n\n\n \n }\n\n\n\n function rolloverLoanWithFlashSwapRewards(\n address _lenderCommitmentForwarder,\n uint256 _loanId, \n\n uint256 _borrowerAmount, //an additional amount borrower may have to add\n uint256 _rewardAmount,\n address _rewardRecipient,\n uint256 _atmId, //optional, just for analytics \n\n FlashSwapArgs calldata _flashSwapArgs, \n\n AcceptCommitmentArgs calldata _acceptCommitmentArgs\n\n ) external {\n address borrower = TELLER_V2.getLoanBorrower(_loanId);\n require(borrower == msg.sender, \"Must be borrower\");\n\n\n {\n // Get lending token and balance before\n address lendingToken = TELLER_V2.getLoanLendingToken(_loanId);\n\n require( \n _rewardAmount <= _flashSwapArgs.flashAmount / 10 ,\n \"Excessive reward amount\" );\n\n if (_borrowerAmount > 0) {\n TransferHelper.safeTransferFrom(lendingToken, borrower, address(this), _borrowerAmount); \n }\n } \n \n\n IUniswapV3Pool( \n getUniswapPoolAddress (\n _flashSwapArgs.token0,\n _flashSwapArgs.token1,\n _flashSwapArgs.fee\n )\n ).flash(\n address(this),\n _flashSwapArgs.borrowToken1 ? 0 : _flashSwapArgs.flashAmount, \n _flashSwapArgs.borrowToken1 ? _flashSwapArgs.flashAmount : 0, \n abi.encode( \n RolloverCallbackArgs({\n lenderCommitmentForwarder : _lenderCommitmentForwarder,\n loanId: _loanId,\n borrower: borrower,\n borrowerAmount: _borrowerAmount, // need this ? \n rewardRecipient: _rewardRecipient,\n rewardAmount: _rewardAmount,\n atmId: _atmId, \n acceptCommitmentArgs: abi.encode(_acceptCommitmentArgs), \n flashSwapArgs: abi.encode( _flashSwapArgs) \n \n })\n\n )\n );\n\n\n \n }\n\n\n\n\n /*\n @dev _verifyFlashCallback ensures that only the uniswap pool can call this method \n */\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external override {\n RolloverCallbackArgs memory _rolloverArgs = abi.decode(data, (RolloverCallbackArgs));\n \n\n\n\n AcceptCommitmentArgs memory acceptCommitmentArgs = abi.decode(\n _rolloverArgs.acceptCommitmentArgs,\n (AcceptCommitmentArgs)\n );\n\n FlashSwapArgs memory flashSwapArgs = abi.decode(\n\n _rolloverArgs.flashSwapArgs,\n (FlashSwapArgs)\n\n );\n\n \n PoolAddress.PoolKey memory poolKey =\n PoolAddress.PoolKey({token0: flashSwapArgs.token0, token1: flashSwapArgs.token1, fee: flashSwapArgs.fee}); \n\n _verifyFlashCallback( factory , poolKey );\n \n \n\n address flashToken = flashSwapArgs.borrowToken1 ? flashSwapArgs.token1: flashSwapArgs.token0 ; \n uint256 flashFee = flashSwapArgs.borrowToken1 ? fee1: fee0 ;\n\n\n\n uint256 repaymentAmount = _repayLoanFull(\n _rolloverArgs.loanId, \n flashToken,\n flashSwapArgs.flashAmount\n );\n\n \n\n // Accept commitment and receive funds to this contract \n (uint256 newLoanId, uint256 acceptCommitmentAmount) = _acceptCommitment(\n _rolloverArgs.lenderCommitmentForwarder,\n _rolloverArgs.borrower,\n flashToken,\n acceptCommitmentArgs\n );\n\n \n uint256 amountOwedToPool = LowGasSafeMath.add(flashSwapArgs.flashAmount, flashFee) ; \n \n // what is the point of this ?? \n // TransferHelper.safeApprove(flashToken, address(this), amountOwedToPool);\n \n // msg.sender is the uniswap pool \n if (amountOwedToPool > 0) pay(flashToken, address(this), msg.sender, amountOwedToPool);\n \n \n // send any dust to the borrower\n uint256 fundsRemaining = flashSwapArgs.flashAmount + \n acceptCommitmentAmount +\n _rolloverArgs.borrowerAmount -\n repaymentAmount -\n amountOwedToPool;\n \n \n if (fundsRemaining > 0) {\n\n if (_rolloverArgs.rewardAmount > 0){ \n\n fundsRemaining -= _rolloverArgs.rewardAmount;\n TransferHelper.safeTransfer(flashToken, _rolloverArgs.rewardRecipient, _rolloverArgs.rewardAmount) ;\n\n emit RolloverWithReferral( newLoanId, flashToken, _rolloverArgs.rewardRecipient, _rolloverArgs.rewardAmount, _rolloverArgs.atmId ) ; \n \n }\n\n TransferHelper.safeTransfer(flashToken, _rolloverArgs.borrower, fundsRemaining) ;\n \n \n }\n\n\n\n emit RolloverLoanComplete(\n _rolloverArgs.borrower,\n _rolloverArgs.loanId,\n newLoanId,\n fundsRemaining\n );\n\n \n\n\n }\n\n\n \n function _verifyFlashCallback( \n address _factory,\n PoolAddress.PoolKey memory _poolKey \n ) internal virtual {\n\n CallbackValidation.verifyCallback(_factory, _poolKey); //verifies that only uniswap contract can call this fn \n\n }\n\n\n function getUniswapPoolAddress( \n address token0,\n address token1,\n uint24 fee\n ) public view virtual returns (address) {\n\n return IUniswapV3Factory(factory).getPool(token0,token1,fee);\n\n }\n\n\n /**\n *\n *\n * @notice Internal function that repays a loan in full on behalf of this contract.\n *\n * @dev The function first calculates the funds held by the contract before repayment, then approves\n * the repayment amount to the TellerV2 contract and finally repays the loan in full.\n *\n * @param _bidId Identifier of the loan to be repaid.\n * @param _principalToken The token in which the loan was originated.\n * @param _repayAmount The amount to be repaid.\n *\n * @return repayAmount_ The actual amount that was used for repayment.\n */\n function _repayLoanFull(\n uint256 _bidId,\n address _principalToken,\n uint256 _repayAmount\n ) internal returns (uint256 repayAmount_) {\n uint256 fundsBeforeRepayment = IERC20Upgradeable(_principalToken)\n .balanceOf(address(this));\n\n IERC20Upgradeable(_principalToken).approve(\n address(TELLER_V2),\n _repayAmount\n );\n TELLER_V2.repayLoanFull(_bidId);\n\n uint256 fundsAfterRepayment = IERC20Upgradeable(_principalToken)\n .balanceOf(address(this));\n\n repayAmount_ = fundsBeforeRepayment - fundsAfterRepayment;\n }\n\n /**\n *\n *\n * @notice Accepts a loan commitment using either a Merkle proof or standard method.\n *\n * @dev The function first checks if a Merkle proof is provided, based on which it calls the relevant\n * `acceptCommitment` function in the LenderCommitmentForwarder contract.\n *\n * @param borrower The address of the borrower for whom the commitment is being accepted.\n * @param principalToken The token in which the loan is being accepted.\n * @param _commitmentArgs The arguments necessary for accepting the commitment.\n *\n * @return bidId_ Identifier of the accepted loan.\n * @return acceptCommitmentAmount_ The amount received from accepting the commitment.\n */\n function _acceptCommitment(\n address lenderCommitmentForwarder,\n address borrower,\n address principalToken,\n AcceptCommitmentArgs memory _commitmentArgs\n )\n internal\n virtual\n returns (uint256 bidId_, uint256 acceptCommitmentAmount_)\n {\n uint256 fundsBeforeAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n\n\n\n if (_commitmentArgs.smartCommitmentAddress != address(0)) {\n\n bytes memory responseData = address(lenderCommitmentForwarder)\n .functionCall(\n abi.encodePacked(\n abi.encodeWithSelector(\n ISmartCommitmentForwarder\n .acceptSmartCommitmentWithRecipient\n .selector,\n _commitmentArgs.smartCommitmentAddress,\n _commitmentArgs.principalAmount,\n _commitmentArgs.collateralAmount,\n _commitmentArgs.collateralTokenId,\n _commitmentArgs.collateralTokenAddress,\n address(this),\n _commitmentArgs.interestRate,\n _commitmentArgs.loanDuration\n ),\n borrower //cant be msg.sender because of the flash flow\n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\n\n\n }else { \n\n bool usingMerkleProof = _commitmentArgs.merkleProof.length > 0;\n\n if (usingMerkleProof) {\n bytes memory responseData = address(lenderCommitmentForwarder)\n .functionCall(\n abi.encodePacked(\n abi.encodeWithSelector(\n ILenderCommitmentForwarder\n .acceptCommitmentWithRecipientAndProof\n .selector,\n _commitmentArgs.commitmentId,\n _commitmentArgs.principalAmount,\n _commitmentArgs.collateralAmount,\n _commitmentArgs.collateralTokenId,\n _commitmentArgs.collateralTokenAddress,\n address(this),\n _commitmentArgs.interestRate,\n _commitmentArgs.loanDuration,\n _commitmentArgs.merkleProof\n ),\n borrower //cant be msg.sender because of the flash flow\n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\n } else {\n bytes memory responseData = address(lenderCommitmentForwarder)\n .functionCall(\n abi.encodePacked(\n abi.encodeWithSelector(\n ILenderCommitmentForwarder\n .acceptCommitmentWithRecipient\n .selector,\n _commitmentArgs.commitmentId,\n _commitmentArgs.principalAmount,\n _commitmentArgs.collateralAmount,\n _commitmentArgs.collateralTokenId,\n _commitmentArgs.collateralTokenAddress,\n address(this),\n _commitmentArgs.interestRate,\n _commitmentArgs.loanDuration\n ),\n borrower //cant be msg.sender because of the flash flow\n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\n }\n\n }\n\n uint256 fundsAfterAcceptCommitment = IERC20Upgradeable(principalToken)\n .balanceOf(address(this));\n acceptCommitmentAmount_ =\n fundsAfterAcceptCommitment -\n fundsBeforeAcceptCommitment;\n }\n\n \n\n /**\n * @notice Calculates the amount for loan rollover, determining if the borrower owes or receives funds.\n \n */\n function calculateRolloverAmount(\n uint16 marketFeePct,\n uint16 protocolFeePct, \n uint256 _loanId, \n uint256 principalAmount,\n uint256 _rewardAmount, \n uint16 _flashloanFeePct, // 3000 means 0.3% in uniswap terms\n uint256 _timestamp\n ) external view returns (uint256 _flashAmount, int256 _borrowerAmount) {\n \n\n Payment memory repayAmountOwed = TELLER_V2.calculateAmountOwed(\n _loanId,\n _timestamp\n );\n\n uint256 commitmentPrincipalRequested = principalAmount; // _commitmentArgs.principalAmount;\n uint256 amountToMarketplace = commitmentPrincipalRequested.percent(\n marketFeePct\n );\n uint256 amountToProtocol = commitmentPrincipalRequested.percent(\n protocolFeePct\n );\n\n uint256 commitmentPrincipalReceived = commitmentPrincipalRequested -\n amountToMarketplace -\n amountToProtocol;\n\n // by default, we will flash exactly what we need to do relayLoanFull\n uint256 repayFullAmount = repayAmountOwed.principal +\n repayAmountOwed.interest;\n\n _flashAmount = repayFullAmount;\n uint256 _flashLoanFee = _flashAmount.percent(_flashloanFeePct, 4 );\n\n _borrowerAmount =\n int256(commitmentPrincipalReceived) -\n int256(repayFullAmount) -\n int256(_flashLoanFee) -\n int256(_rewardAmount);\n\n \n }\n\n\n function getMarketIdForCommitment(\n address _lenderCommitmentForwarder, \n uint256 _commitmentId\n ) external view returns (uint256) {\n return _getMarketIdForCommitment(_lenderCommitmentForwarder, _commitmentId); \n }\n\n function getMarketFeePct(\n uint256 _marketId\n ) external view returns (uint16) {\n return _getMarketFeePct(_marketId); \n }\n \n\n /**\n * @notice Retrieves the market ID associated with a given commitment.\n * @param _commitmentId The ID of the commitment for which to fetch the market ID.\n * @return The ID of the market associated with the provided commitment.\n */\n function _getMarketIdForCommitment(address _lenderCommitmentForwarder, uint256 _commitmentId)\n internal\n view\n returns (uint256)\n {\n return ILenderCommitmentForwarder(_lenderCommitmentForwarder).getCommitmentMarketId(_commitmentId);\n }\n\n /**\n * @notice Fetches the marketplace fee percentage for a given market ID.\n * @param _marketId The ID of the market for which to fetch the fee percentage.\n * @return The marketplace fee percentage for the provided market ID.\n */\n function _getMarketFeePct(uint256 _marketId)\n internal\n view\n returns (uint16)\n {\n address _marketRegistryAddress = ITellerV2Storage(address(TELLER_V2))\n .marketRegistry();\n\n return\n IMarketRegistry(_marketRegistryAddress).getMarketplaceFee(\n _marketId\n );\n }\n\n \n}\n" + }, + "contracts/LenderCommitmentForwarder/extensions/rollover/SwapRolloverLoan.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n \nimport \"./SwapRolloverLoan_G1.sol\";\n\ncontract SwapRolloverLoan is SwapRolloverLoan_G1 {\n constructor(\n address _tellerV2, \n address _factory,\n address _WETH9\n )\n SwapRolloverLoan_G1(\n _tellerV2,\n _factory,\n _WETH9\n )\n {}\n}\n" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_G1.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"../TellerV2MarketForwarder_G1.sol\";\n\n// Interfaces\nimport \"../interfaces/ICollateralManager.sol\";\nimport { Collateral, CollateralType } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\n\n// Libraries\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol\";\n\ncontract LenderCommitmentForwarder_G1 is TellerV2MarketForwarder_G1 {\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n\n enum CommitmentCollateralType {\n NONE, // no collateral required\n ERC20,\n ERC721,\n ERC1155,\n ERC721_ANY_ID,\n ERC1155_ANY_ID,\n ERC721_MERKLE_PROOF,\n ERC1155_MERKLE_PROOF\n }\n\n /**\n * @notice Details about a lender's capital commitment.\n * @param maxPrincipal Amount of tokens being committed by the lender. Max amount that can be loaned.\n * @param expiration Expiration time in seconds, when the commitment expires.\n * @param maxDuration Length of time, in seconds that the lender's capital can be lent out for.\n * @param minInterestRate Minimum Annual percentage to be applied for loans using the lender's capital.\n * @param collateralTokenAddress The address for the token contract that must be used to provide collateral for loans for this commitment.\n * @param maxPrincipalPerCollateralAmount The amount of principal that can be used for a loan per each unit of collateral, expanded additionally by principal decimals.\n * @param collateralTokenType The type of asset of the collateralTokenAddress (ERC20, ERC721, or ERC1155).\n * @param lender The address of the lender for this commitment.\n * @param marketId The market id for this commitment.\n * @param principalTokenAddress The address for the token contract that will be used to provide principal for loans of this commitment.\n */\n struct Commitment {\n uint256 maxPrincipal;\n uint32 expiration;\n uint32 maxDuration;\n uint16 minInterestRate;\n address collateralTokenAddress;\n uint256 collateralTokenId; //we use this for the MerkleRootHash for type ERC721_MERKLE_PROOF\n uint256 maxPrincipalPerCollateralAmount;\n CommitmentCollateralType collateralTokenType;\n address lender;\n uint256 marketId;\n address principalTokenAddress;\n }\n\n // CommitmentId => commitment\n mapping(uint256 => Commitment) public commitments;\n\n uint256 commitmentCount;\n\n //https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/utils/structs/EnumerableSetUpgradeable.sol\n mapping(uint256 => EnumerableSetUpgradeable.AddressSet)\n internal commitmentBorrowersList;\n\n mapping(uint256 => uint256) public commitmentPrincipalAccepted;\n\n /**\n * @notice This event is emitted when a lender's commitment is created.\n * @param lender The address of the lender.\n * @param marketId The Id of the market the commitment applies to.\n * @param lendingToken The address of the asset being committed.\n * @param tokenAmount The amount of the asset being committed.\n */\n event CreatedCommitment(\n uint256 indexed commitmentId,\n address lender,\n uint256 marketId,\n address lendingToken,\n uint256 tokenAmount\n );\n\n /**\n * @notice This event is emitted when a lender's commitment is updated.\n * @param commitmentId The id of the commitment that was updated.\n * @param lender The address of the lender.\n * @param marketId The Id of the market the commitment applies to.\n * @param lendingToken The address of the asset being committed.\n * @param tokenAmount The amount of the asset being committed.\n */\n event UpdatedCommitment(\n uint256 indexed commitmentId,\n address lender,\n uint256 marketId,\n address lendingToken,\n uint256 tokenAmount\n );\n\n /**\n * @notice This event is emitted when the allowed borrowers for a commitment is updated.\n * @param commitmentId The id of the commitment that was updated.\n */\n event UpdatedCommitmentBorrowers(uint256 indexed commitmentId);\n\n /**\n * @notice This event is emitted when a lender's commitment has been deleted.\n * @param commitmentId The id of the commitment that was deleted.\n */\n event DeletedCommitment(uint256 indexed commitmentId);\n\n /**\n * @notice This event is emitted when a lender's commitment is exercised for a loan.\n * @param commitmentId The id of the commitment that was exercised.\n * @param borrower The address of the borrower.\n * @param tokenAmount The amount of the asset being committed.\n * @param bidId The bid id for the loan from TellerV2.\n */\n event ExercisedCommitment(\n uint256 indexed commitmentId,\n address borrower,\n uint256 tokenAmount,\n uint256 bidId\n );\n\n error InsufficientCommitmentAllocation(\n uint256 allocated,\n uint256 requested\n );\n error InsufficientBorrowerCollateral(uint256 required, uint256 actual);\n\n /** Modifiers **/\n\n modifier commitmentLender(uint256 _commitmentId) {\n require(\n commitments[_commitmentId].lender == _msgSender(),\n \"unauthorized commitment lender\"\n );\n _;\n }\n\n function validateCommitment(Commitment storage _commitment) internal {\n require(\n _commitment.expiration > uint32(block.timestamp),\n \"expired commitment\"\n );\n require(\n _commitment.maxPrincipal > 0,\n \"commitment principal allocation 0\"\n );\n\n if (_commitment.collateralTokenType != CommitmentCollateralType.NONE) {\n require(\n _commitment.maxPrincipalPerCollateralAmount > 0,\n \"commitment collateral ratio 0\"\n );\n\n if (\n _commitment.collateralTokenType ==\n CommitmentCollateralType.ERC20\n ) {\n require(\n _commitment.collateralTokenId == 0,\n \"commitment collateral token id must be 0 for ERC20\"\n );\n }\n }\n }\n\n /** External Functions **/\n\n constructor(address _protocolAddress, address _marketRegistry)\n TellerV2MarketForwarder_G1(_protocolAddress, _marketRegistry)\n {}\n\n /**\n * @notice Creates a loan commitment from a lender for a market.\n * @param _commitment The new commitment data expressed as a struct\n * @param _borrowerAddressList The array of borrowers that are allowed to accept loans using this commitment\n * @return commitmentId_ returns the commitmentId for the created commitment\n */\n function createCommitment(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList\n ) public returns (uint256 commitmentId_) {\n commitmentId_ = commitmentCount++;\n\n require(\n _commitment.lender == _msgSender(),\n \"unauthorized commitment creator\"\n );\n\n commitments[commitmentId_] = _commitment;\n\n //make sure the commitment data adheres to required specifications and limits\n validateCommitment(commitments[commitmentId_]);\n\n //the borrower allowlists is in a different storage space so we append them to the array with this method s\n _addBorrowersToCommitmentAllowlist(commitmentId_, _borrowerAddressList);\n\n emit CreatedCommitment(\n commitmentId_,\n _commitment.lender,\n _commitment.marketId,\n _commitment.principalTokenAddress,\n _commitment.maxPrincipal\n );\n }\n\n /**\n * @notice Updates the commitment of a lender to a market.\n * @param _commitmentId The Id of the commitment to update.\n * @param _commitment The new commitment data expressed as a struct\n */\n function updateCommitment(\n uint256 _commitmentId,\n Commitment calldata _commitment\n ) public commitmentLender(_commitmentId) {\n require(\n _commitment.lender == _msgSender(),\n \"Commitment lender cannot be updated.\"\n );\n\n require(\n _commitment.principalTokenAddress ==\n commitments[_commitmentId].principalTokenAddress,\n \"Principal token address cannot be updated.\"\n );\n require(\n _commitment.marketId == commitments[_commitmentId].marketId,\n \"Market Id cannot be updated.\"\n );\n\n commitments[_commitmentId] = _commitment;\n\n //make sure the commitment data still adheres to required specifications and limits\n validateCommitment(commitments[_commitmentId]);\n\n emit UpdatedCommitment(\n _commitmentId,\n _commitment.lender,\n _commitment.marketId,\n _commitment.principalTokenAddress,\n _commitment.maxPrincipal\n );\n }\n\n /**\n * @notice Updates the borrowers allowed to accept a commitment\n * @param _commitmentId The Id of the commitment to update.\n * @param _borrowerAddressList The array of borrowers that are allowed to accept loans using this commitment\n */\n function addCommitmentBorrowers(\n uint256 _commitmentId,\n address[] calldata _borrowerAddressList\n ) public commitmentLender(_commitmentId) {\n _addBorrowersToCommitmentAllowlist(_commitmentId, _borrowerAddressList);\n }\n\n /**\n * @notice Updates the borrowers allowed to accept a commitment\n * @param _commitmentId The Id of the commitment to update.\n * @param _borrowerAddressList The array of borrowers that are allowed to accept loans using this commitment\n */\n function removeCommitmentBorrowers(\n uint256 _commitmentId,\n address[] calldata _borrowerAddressList\n ) public commitmentLender(_commitmentId) {\n _removeBorrowersFromCommitmentAllowlist(\n _commitmentId,\n _borrowerAddressList\n );\n }\n\n /**\n * @notice Adds a borrower to the allowlist for a commmitment.\n * @param _commitmentId The id of the commitment that will allow the new borrower\n * @param _borrowerArray the address array of the borrowers that will be allowed to accept loans using the commitment\n */\n function _addBorrowersToCommitmentAllowlist(\n uint256 _commitmentId,\n address[] calldata _borrowerArray\n ) internal {\n for (uint256 i = 0; i < _borrowerArray.length; i++) {\n commitmentBorrowersList[_commitmentId].add(_borrowerArray[i]);\n }\n emit UpdatedCommitmentBorrowers(_commitmentId);\n }\n\n /**\n * @notice Removes a borrower to the allowlist for a commmitment.\n * @param _commitmentId The id of the commitment that will allow the new borrower\n * @param _borrowerArray the address array of the borrowers that will be allowed to accept loans using the commitment\n */\n function _removeBorrowersFromCommitmentAllowlist(\n uint256 _commitmentId,\n address[] calldata _borrowerArray\n ) internal {\n for (uint256 i = 0; i < _borrowerArray.length; i++) {\n commitmentBorrowersList[_commitmentId].remove(_borrowerArray[i]);\n }\n emit UpdatedCommitmentBorrowers(_commitmentId);\n }\n\n /**\n * @notice Removes the commitment of a lender to a market.\n * @param _commitmentId The id of the commitment to delete.\n */\n function deleteCommitment(uint256 _commitmentId)\n public\n commitmentLender(_commitmentId)\n {\n delete commitments[_commitmentId];\n delete commitmentBorrowersList[_commitmentId];\n emit DeletedCommitment(_commitmentId);\n }\n\n /**\n * @notice Accept the commitment to submitBid and acceptBid using the funds\n * @dev LoanDuration must be longer than the market payment cycle\n * @param _commitmentId The id of the commitment being accepted.\n * @param _principalAmount The amount of currency to borrow for the loan.\n * @param _collateralAmount The amount of collateral to use for the loan.\n * @param _collateralTokenId The tokenId of collateral to use for the loan if ERC721 or ERC1155.\n * @param _collateralTokenAddress The contract address to use for the loan collateral tokens.\n * @param _interestRate The interest rate APY to use for the loan in basis points.\n * @param _loanDuration The overall duration for the loan. Must be longer than market payment cycle duration.\n * @return bidId The ID of the loan that was created on TellerV2\n */\n function acceptCommitment(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n uint16 _interestRate,\n uint32 _loanDuration\n ) external returns (uint256 bidId) {\n require(\n commitments[_commitmentId].collateralTokenType <=\n CommitmentCollateralType.ERC1155_ANY_ID,\n \"Invalid commitment collateral type\"\n );\n\n return\n _acceptCommitment(\n _commitmentId,\n _principalAmount,\n _collateralAmount,\n _collateralTokenId,\n _collateralTokenAddress,\n _interestRate,\n _loanDuration\n );\n }\n\n /**\n * @notice Accept the commitment to submitBid and acceptBid using the funds\n * @dev LoanDuration must be longer than the market payment cycle\n * @param _commitmentId The id of the commitment being accepted.\n * @param _principalAmount The amount of currency to borrow for the loan.\n * @param _collateralAmount The amount of collateral to use for the loan.\n * @param _collateralTokenId The tokenId of collateral to use for the loan if ERC721 or ERC1155.\n * @param _collateralTokenAddress The contract address to use for the loan collateral tokens.\n * @param _interestRate The interest rate APY to use for the loan in basis points.\n * @param _loanDuration The overall duration for the loan. Must be longer than market payment cycle duration.\n * @param _merkleProof An array of bytes32 which are the roots down the merkle tree, the merkle proof.\n * @return bidId The ID of the loan that was created on TellerV2\n */\n function acceptCommitmentWithProof(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n uint16 _interestRate,\n uint32 _loanDuration,\n bytes32[] calldata _merkleProof\n ) external returns (uint256 bidId) {\n require(\n commitments[_commitmentId].collateralTokenType ==\n CommitmentCollateralType.ERC721_MERKLE_PROOF ||\n commitments[_commitmentId].collateralTokenType ==\n CommitmentCollateralType.ERC1155_MERKLE_PROOF,\n \"Invalid commitment collateral type\"\n );\n\n bytes32 _merkleRoot = bytes32(\n commitments[_commitmentId].collateralTokenId\n );\n bytes32 _leaf = keccak256(abi.encodePacked(_collateralTokenId));\n\n //make sure collateral token id is a leaf within the proof\n require(\n MerkleProofUpgradeable.verifyCalldata(\n _merkleProof,\n _merkleRoot,\n _leaf\n ),\n \"Invalid proof\"\n );\n\n return\n _acceptCommitment(\n _commitmentId,\n _principalAmount,\n _collateralAmount,\n _collateralTokenId,\n _collateralTokenAddress,\n _interestRate,\n _loanDuration\n );\n }\n\n /**\n * @notice Accept the commitment to submitBid and acceptBid using the funds\n * @dev LoanDuration must be longer than the market payment cycle\n * @param _commitmentId The id of the commitment being accepted.\n * @param _principalAmount The amount of currency to borrow for the loan.\n * @param _collateralAmount The amount of collateral to use for the loan.\n * @param _collateralTokenId The tokenId of collateral to use for the loan if ERC721 or ERC1155.\n * @param _collateralTokenAddress The contract address to use for the loan collateral tokens.\n * @param _interestRate The interest rate APY to use for the loan in basis points.\n * @param _loanDuration The overall duration for the loan. Must be longer than market payment cycle duration.\n * @return bidId The ID of the loan that was created on TellerV2\n */\n function _acceptCommitment(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n uint16 _interestRate,\n uint32 _loanDuration\n ) internal returns (uint256 bidId) {\n address borrower = _msgSender();\n\n Commitment storage commitment = commitments[_commitmentId];\n\n //make sure the commitment data adheres to required specifications and limits\n validateCommitment(commitment);\n\n //the collateral token of the commitment should be the same as the acceptor expects\n require(\n _collateralTokenAddress == commitment.collateralTokenAddress,\n \"Mismatching collateral token\"\n );\n //the interest rate must be at least as high has the commitment demands. The borrower can use a higher interest rate although that would not be beneficial to the borrower.\n require(\n _interestRate >= commitment.minInterestRate,\n \"Invalid interest rate\"\n );\n //the loan duration must be less than the commitment max loan duration. The lender who made the commitment expects the money to be returned before this window.\n require(\n _loanDuration <= commitment.maxDuration,\n \"Invalid loan max duration\"\n );\n\n require(\n commitmentPrincipalAccepted[bidId] <= commitment.maxPrincipal,\n \"Invalid loan max principal\"\n );\n\n require(\n commitmentBorrowersList[_commitmentId].length() == 0 ||\n commitmentBorrowersList[_commitmentId].contains(borrower),\n \"unauthorized commitment borrower\"\n );\n //require that the borrower accepting the commitment cannot borrow more than the commitments max principal\n if (_principalAmount > commitment.maxPrincipal) {\n revert InsufficientCommitmentAllocation({\n allocated: commitment.maxPrincipal,\n requested: _principalAmount\n });\n }\n\n uint256 requiredCollateral = getRequiredCollateral(\n _principalAmount,\n commitment.maxPrincipalPerCollateralAmount,\n commitment.collateralTokenType,\n commitment.collateralTokenAddress,\n commitment.principalTokenAddress\n );\n\n if (_collateralAmount < requiredCollateral) {\n revert InsufficientBorrowerCollateral({\n required: requiredCollateral,\n actual: _collateralAmount\n });\n }\n\n //ERC721 assets must have a quantity of 1\n if (\n commitment.collateralTokenType == CommitmentCollateralType.ERC721 ||\n commitment.collateralTokenType ==\n CommitmentCollateralType.ERC721_ANY_ID ||\n commitment.collateralTokenType ==\n CommitmentCollateralType.ERC721_MERKLE_PROOF\n ) {\n require(\n _collateralAmount == 1,\n \"invalid commitment collateral amount for ERC721\"\n );\n }\n\n //ERC721 and ERC1155 types strictly enforce a specific token Id. ERC721_ANY and ERC1155_ANY do not.\n if (\n commitment.collateralTokenType == CommitmentCollateralType.ERC721 ||\n commitment.collateralTokenType == CommitmentCollateralType.ERC1155\n ) {\n require(\n commitment.collateralTokenId == _collateralTokenId,\n \"invalid commitment collateral tokenId\"\n );\n }\n\n commitmentPrincipalAccepted[_commitmentId] += _principalAmount;\n\n require(\n commitmentPrincipalAccepted[_commitmentId] <=\n commitment.maxPrincipal,\n \"Exceeds max principal of commitment\"\n );\n\n bidId = _submitBidFromCommitment(\n borrower,\n commitment.marketId,\n commitment.principalTokenAddress,\n _principalAmount,\n commitment.collateralTokenAddress,\n _collateralAmount,\n _collateralTokenId,\n commitment.collateralTokenType,\n _loanDuration,\n _interestRate\n );\n\n _acceptBid(bidId, commitment.lender);\n\n emit ExercisedCommitment(\n _commitmentId,\n borrower,\n _principalAmount,\n bidId\n );\n }\n\n /**\n * @notice Calculate the amount of collateral required to borrow a loan with _principalAmount of principal\n * @param _principalAmount The amount of currency to borrow for the loan.\n * @param _maxPrincipalPerCollateralAmount The ratio for the amount of principal that can be borrowed for each amount of collateral. This is expanded additionally by the principal decimals.\n * @param _collateralTokenType The type of collateral for the loan either ERC20, ERC721, ERC1155, or None.\n * @param _collateralTokenAddress The contract address for the collateral for the loan.\n * @param _principalTokenAddress The contract address for the principal for the loan.\n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount,\n CommitmentCollateralType _collateralTokenType,\n address _collateralTokenAddress,\n address _principalTokenAddress\n ) public view virtual returns (uint256) {\n if (_collateralTokenType == CommitmentCollateralType.NONE) {\n return 0;\n }\n\n uint8 collateralDecimals;\n uint8 principalDecimals = IERC20MetadataUpgradeable(\n _principalTokenAddress\n ).decimals();\n\n if (_collateralTokenType == CommitmentCollateralType.ERC20) {\n collateralDecimals = IERC20MetadataUpgradeable(\n _collateralTokenAddress\n ).decimals();\n }\n\n /*\n * The principalAmount is expanded by (collateralDecimals+principalDecimals) to increase precision\n * and then it is divided by _maxPrincipalPerCollateralAmount which should already been expanded by principalDecimals\n */\n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n (10**(collateralDecimals + principalDecimals)),\n _maxPrincipalPerCollateralAmount,\n MathUpgradeable.Rounding.Up\n );\n }\n\n /**\n * @notice Return the array of borrowers that are allowlisted for a commitment\n * @param _commitmentId The commitment id for the commitment to query.\n * @return borrowers_ An array of addresses restricted to accept the commitment. Empty array means unrestricted.\n */\n function getCommitmentBorrowers(uint256 _commitmentId)\n external\n view\n returns (address[] memory borrowers_)\n {\n borrowers_ = commitmentBorrowersList[_commitmentId].values();\n }\n\n /**\n * @notice Internal function to submit a bid to the lending protocol using a commitment\n * @param _borrower The address of the borrower for the loan.\n * @param _marketId The id for the market of the loan in the lending protocol.\n * @param _principalTokenAddress The contract address for the principal token.\n * @param _principalAmount The amount of principal to borrow for the loan.\n * @param _collateralTokenAddress The contract address for the collateral token.\n * @param _collateralAmount The amount of collateral to use for the loan.\n * @param _collateralTokenId The tokenId for the collateral (if it is ERC721 or ERC1155).\n * @param _collateralTokenType The type of collateral token (ERC20,ERC721,ERC1177,None).\n * @param _loanDuration The duration of the loan in seconds delta. Must be longer than loan payment cycle for the market.\n * @param _interestRate The amount of interest APY for the loan expressed in basis points.\n */\n function _submitBidFromCommitment(\n address _borrower,\n uint256 _marketId,\n address _principalTokenAddress,\n uint256 _principalAmount,\n address _collateralTokenAddress,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n CommitmentCollateralType _collateralTokenType,\n uint32 _loanDuration,\n uint16 _interestRate\n ) internal returns (uint256 bidId) {\n CreateLoanArgs memory createLoanArgs;\n createLoanArgs.marketId = _marketId;\n createLoanArgs.lendingToken = _principalTokenAddress;\n createLoanArgs.principal = _principalAmount;\n createLoanArgs.duration = _loanDuration;\n createLoanArgs.interestRate = _interestRate;\n\n Collateral[] memory collateralInfo;\n if (_collateralTokenType != CommitmentCollateralType.NONE) {\n collateralInfo = new Collateral[](1);\n collateralInfo[0] = Collateral({\n _collateralType: _getEscrowCollateralType(_collateralTokenType),\n _tokenId: _collateralTokenId,\n _amount: _collateralAmount,\n _collateralAddress: _collateralTokenAddress\n });\n }\n\n bidId = _submitBidWithCollateral(\n createLoanArgs,\n collateralInfo,\n _borrower\n );\n }\n\n /**\n * @notice Return the collateral type based on the commitmentcollateral type. Collateral type is used in the base lending protocol.\n * @param _type The type of collateral to be used for the loan.\n */\n function _getEscrowCollateralType(CommitmentCollateralType _type)\n internal\n pure\n returns (CollateralType)\n {\n if (_type == CommitmentCollateralType.ERC20) {\n return CollateralType.ERC20;\n }\n if (\n _type == CommitmentCollateralType.ERC721 ||\n _type == CommitmentCollateralType.ERC721_ANY_ID ||\n _type == CommitmentCollateralType.ERC721_MERKLE_PROOF\n ) {\n return CollateralType.ERC721;\n }\n if (\n _type == CommitmentCollateralType.ERC1155 ||\n _type == CommitmentCollateralType.ERC1155_ANY_ID ||\n _type == CommitmentCollateralType.ERC1155_MERKLE_PROOF\n ) {\n return CollateralType.ERC1155;\n }\n\n revert(\"Unknown Collateral Type\");\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// Contracts\nimport \"../TellerV2MarketForwarder_G2.sol\";\n\n// Interfaces\nimport \"../interfaces/ICollateralManager.sol\";\nimport \"../interfaces/ILenderCommitmentForwarder_U2.sol\";\nimport \"./extensions/ExtensionsContextUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\n\nimport { Collateral, CollateralType } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\n\n// Libraries\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol\";\n\nimport \"../interfaces/uniswap/IUniswapV3Pool.sol\";\nimport \"../interfaces/uniswap/IUniswapV3Factory.sol\";\n \n\nimport \"../libraries/uniswap/TickMath.sol\";\nimport \"../libraries/uniswap/FixedPoint96.sol\";\nimport \"../libraries/uniswap/FullMath.sol\";\n\nimport \"../libraries/NumbersLib.sol\";\n\nimport {UniswapPricingLibraryV2} from \"../libraries/UniswapPricingLibraryV2.sol\";\n\n\n\nimport \"./extensions/ExtensionsContextUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n\n\n/*\n\nOnly do decimal expansion if it is an ERC20 not anything else !! \n\n*/\n\ncontract LenderCommitmentForwarder_U2 is\n ExtensionsContextUpgradeable, //this should always be first for upgradeability\n TellerV2MarketForwarder_G2,\n ILenderCommitmentForwarder_U2\n{\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n using NumbersLib for uint256;\n\n // CommitmentId => commitment\n mapping(uint256 => Commitment) public commitments;\n\n uint256 commitmentCount;\n\n //https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/utils/structs/EnumerableSetUpgradeable.sol\n mapping(uint256 => EnumerableSetUpgradeable.AddressSet)\n internal commitmentBorrowersList;\n\n //commitment id => amount \n mapping(uint256 => uint256) public commitmentPrincipalAccepted;\n\n mapping(uint256 => IUniswapPricingLibrary.PoolRouteConfig[]) internal commitmentUniswapPoolRoutes;\n\n mapping(uint256 => uint16) internal commitmentPoolOracleLtvRatio;\n\n //does not take a storage slot\n address immutable UNISWAP_V3_FACTORY;\n\n uint256 immutable STANDARD_EXPANSION_FACTOR = 1e18;\n\n /**\n * @notice This event is emitted when a lender's commitment is created.\n * @param lender The address of the lender.\n * @param marketId The Id of the market the commitment applies to.\n * @param lendingToken The address of the asset being committed.\n * @param tokenAmount The amount of the asset being committed.\n */\n event CreatedCommitment(\n uint256 indexed commitmentId,\n address lender,\n uint256 marketId,\n address lendingToken,\n uint256 tokenAmount\n );\n\n /**\n * @notice This event is emitted when a lender's commitment is updated.\n * @param commitmentId The id of the commitment that was updated.\n * @param lender The address of the lender.\n * @param marketId The Id of the market the commitment applies to.\n * @param lendingToken The address of the asset being committed.\n * @param tokenAmount The amount of the asset being committed.\n */\n event UpdatedCommitment(\n uint256 indexed commitmentId,\n address lender,\n uint256 marketId,\n address lendingToken,\n uint256 tokenAmount\n );\n\n /**\n * @notice This event is emitted when the allowed borrowers for a commitment is updated.\n * @param commitmentId The id of the commitment that was updated.\n */\n event UpdatedCommitmentBorrowers(uint256 indexed commitmentId);\n\n /**\n * @notice This event is emitted when a lender's commitment has been deleted.\n * @param commitmentId The id of the commitment that was deleted.\n */\n event DeletedCommitment(uint256 indexed commitmentId);\n\n /**\n * @notice This event is emitted when a lender's commitment is exercised for a loan.\n * @param commitmentId The id of the commitment that was exercised.\n * @param borrower The address of the borrower.\n * @param tokenAmount The amount of the asset being committed.\n * @param bidId The bid id for the loan from TellerV2.\n */\n event ExercisedCommitment(\n uint256 indexed commitmentId,\n address borrower,\n uint256 tokenAmount,\n uint256 bidId\n );\n\n error InsufficientCommitmentAllocation(\n uint256 allocated,\n uint256 requested\n );\n error InsufficientBorrowerCollateral(uint256 required, uint256 actual);\n\n /** Modifiers **/\n\n modifier commitmentLender(uint256 _commitmentId) {\n require(\n commitments[_commitmentId].lender == _msgSender(),\n \"unauthorized commitment lender\"\n );\n _;\n }\n\n function validateCommitment(Commitment storage _commitment) internal {\n require(\n _commitment.expiration > uint32(block.timestamp),\n \"expired commitment\"\n );\n require(\n _commitment.maxPrincipal > 0,\n \"commitment principal allocation 0\"\n );\n\n if (_commitment.collateralTokenType != CommitmentCollateralType.NONE) {\n require(\n _commitment.maxPrincipalPerCollateralAmount > 0,\n \"commitment collateral ratio 0\"\n );\n\n if (\n _commitment.collateralTokenType ==\n CommitmentCollateralType.ERC20\n ) {\n require(\n _commitment.collateralTokenId == 0,\n \"commitment collateral token id must be 0 for ERC20\"\n );\n }\n }\n }\n\n /** External Functions **/\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _protocolAddress,\n address _marketRegistry,\n address _uniswapV3Factory\n ) TellerV2MarketForwarder_G2(_protocolAddress, _marketRegistry) {\n UNISWAP_V3_FACTORY = _uniswapV3Factory;\n }\n\n /**\n * @notice Creates a loan commitment from a lender for a market.\n * @param _commitment The new commitment data expressed as a struct\n * @param _borrowerAddressList The array of borrowers that are allowed to accept loans using this commitment\n * @return commitmentId_ returns the commitmentId for the created commitment\n */\n function createCommitmentWithUniswap(\n Commitment calldata _commitment,\n address[] calldata _borrowerAddressList,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolRoutes,\n uint16 _poolOracleLtvRatio //generally always between 0 and 100 % , 0 to 10000\n ) public returns (uint256 commitmentId_) {\n commitmentId_ = commitmentCount++;\n \n require(\n _commitment.lender == _msgSender(),\n \"unauthorized commitment creator\"\n );\n\n commitments[commitmentId_] = _commitment;\n\n require(_poolRoutes.length == 0 || _commitment.collateralTokenType == CommitmentCollateralType.ERC20 , \"can only use pool routes with ERC20 collateral\");\n\n\n //routes length of 0 means ignore price oracle limits\n require(_poolRoutes.length <= 2, \"invalid pool routes length\");\n\n \n \n\n for (uint256 i = 0; i < _poolRoutes.length; i++) {\n commitmentUniswapPoolRoutes[commitmentId_].push(_poolRoutes[i]);\n }\n\n commitmentPoolOracleLtvRatio[commitmentId_] = _poolOracleLtvRatio;\n\n //make sure the commitment data adheres to required specifications and limits\n validateCommitment(commitments[commitmentId_]);\n\n //the borrower allowlists is in a different storage space so we append them to the array with this method s\n _addBorrowersToCommitmentAllowlist(commitmentId_, _borrowerAddressList);\n\n emit CreatedCommitment(\n commitmentId_,\n _commitment.lender,\n _commitment.marketId,\n _commitment.principalTokenAddress,\n _commitment.maxPrincipal\n );\n }\n\n /**\n * @notice Updates the commitment of a lender to a market.\n * @param _commitmentId The Id of the commitment to update.\n * @param _commitment The new commitment data expressed as a struct\n */\n function updateCommitment(\n uint256 _commitmentId,\n Commitment calldata _commitment\n ) public commitmentLender(_commitmentId) {\n require(\n _commitment.lender == _msgSender(),\n \"Commitment lender cannot be updated.\"\n );\n\n require(\n _commitment.principalTokenAddress ==\n commitments[_commitmentId].principalTokenAddress,\n \"Principal token address cannot be updated.\"\n );\n require(\n _commitment.marketId == commitments[_commitmentId].marketId,\n \"Market Id cannot be updated.\"\n );\n\n commitments[_commitmentId] = _commitment;\n\n //make sure the commitment data still adheres to required specifications and limits\n validateCommitment(commitments[_commitmentId]);\n\n emit UpdatedCommitment(\n _commitmentId,\n _commitment.lender,\n _commitment.marketId,\n _commitment.principalTokenAddress,\n _commitment.maxPrincipal\n );\n }\n\n /**\n * @notice Updates the borrowers allowed to accept a commitment\n * @param _commitmentId The Id of the commitment to update.\n * @param _borrowerAddressList The array of borrowers that are allowed to accept loans using this commitment\n */\n function addCommitmentBorrowers(\n uint256 _commitmentId,\n address[] calldata _borrowerAddressList\n ) public commitmentLender(_commitmentId) {\n _addBorrowersToCommitmentAllowlist(_commitmentId, _borrowerAddressList);\n }\n\n /**\n * @notice Updates the borrowers allowed to accept a commitment\n * @param _commitmentId The Id of the commitment to update.\n * @param _borrowerAddressList The array of borrowers that are allowed to accept loans using this commitment\n */\n function removeCommitmentBorrowers(\n uint256 _commitmentId,\n address[] calldata _borrowerAddressList\n ) public commitmentLender(_commitmentId) {\n _removeBorrowersFromCommitmentAllowlist(\n _commitmentId,\n _borrowerAddressList\n );\n }\n\n /**\n * @notice Adds a borrower to the allowlist for a commmitment.\n * @param _commitmentId The id of the commitment that will allow the new borrower\n * @param _borrowerArray the address array of the borrowers that will be allowed to accept loans using the commitment\n */\n function _addBorrowersToCommitmentAllowlist(\n uint256 _commitmentId,\n address[] calldata _borrowerArray\n ) internal {\n for (uint256 i = 0; i < _borrowerArray.length; i++) {\n commitmentBorrowersList[_commitmentId].add(_borrowerArray[i]);\n }\n emit UpdatedCommitmentBorrowers(_commitmentId);\n }\n\n /**\n * @notice Removes a borrower to the allowlist for a commmitment.\n * @param _commitmentId The id of the commitment that will allow the new borrower\n * @param _borrowerArray the address array of the borrowers that will be allowed to accept loans using the commitment\n */\n function _removeBorrowersFromCommitmentAllowlist(\n uint256 _commitmentId,\n address[] calldata _borrowerArray\n ) internal {\n for (uint256 i = 0; i < _borrowerArray.length; i++) {\n commitmentBorrowersList[_commitmentId].remove(_borrowerArray[i]);\n }\n emit UpdatedCommitmentBorrowers(_commitmentId);\n }\n\n /**\n * @notice Removes the commitment of a lender to a market.\n * @param _commitmentId The id of the commitment to delete.\n */\n function deleteCommitment(uint256 _commitmentId)\n public\n commitmentLender(_commitmentId)\n {\n delete commitments[_commitmentId];\n delete commitmentBorrowersList[_commitmentId];\n emit DeletedCommitment(_commitmentId);\n }\n\n /**\n * @notice Accept the commitment to submitBid and acceptBid using the funds\n * @dev LoanDuration must be longer than the market payment cycle\n * @param _commitmentId The id of the commitment being accepted.\n * @param _principalAmount The amount of currency to borrow for the loan.\n * @param _collateralAmount The amount of collateral to use for the loan.\n * @param _collateralTokenId The tokenId of collateral to use for the loan if ERC721 or ERC1155.\n * @param _collateralTokenAddress The contract address to use for the loan collateral tokens.\n * @param _recipient The address to receive the loan funds.\n * @param _interestRate The interest rate APY to use for the loan in basis points.\n * @param _loanDuration The overall duration for the loan. Must be longer than market payment cycle duration.\n * @return bidId The ID of the loan that was created on TellerV2\n */\n function acceptCommitmentWithRecipient(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration\n ) public returns (uint256 bidId) {\n require(\n commitments[_commitmentId].collateralTokenType <=\n CommitmentCollateralType.ERC1155_ANY_ID,\n \"Invalid commitment collateral type\"\n );\n\n return\n _acceptCommitment(\n _commitmentId,\n _principalAmount,\n _collateralAmount,\n _collateralTokenId,\n _collateralTokenAddress,\n _recipient,\n _interestRate,\n _loanDuration\n );\n }\n\n function acceptCommitment(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n uint16 _interestRate,\n uint32 _loanDuration\n ) public returns (uint256 bidId) {\n return\n acceptCommitmentWithRecipient(\n _commitmentId,\n _principalAmount,\n _collateralAmount,\n _collateralTokenId,\n _collateralTokenAddress,\n address(0),\n _interestRate,\n _loanDuration\n );\n }\n\n /**\n * @notice Accept the commitment to submitBid and acceptBid using the funds\n * @dev LoanDuration must be longer than the market payment cycle\n * @param _commitmentId The id of the commitment being accepted.\n * @param _principalAmount The amount of currency to borrow for the loan.\n * @param _collateralAmount The amount of collateral to use for the loan.\n * @param _collateralTokenId The tokenId of collateral to use for the loan if ERC721 or ERC1155.\n * @param _collateralTokenAddress The contract address to use for the loan collateral tokens.\n * @param _recipient The address to receive the loan funds.\n * @param _interestRate The interest rate APY to use for the loan in basis points.\n * @param _loanDuration The overall duration for the loan. Must be longer than market payment cycle duration.\n * @param _merkleProof An array of bytes32 which are the roots down the merkle tree, the merkle proof.\n * @return bidId The ID of the loan that was created on TellerV2\n */\n function acceptCommitmentWithRecipientAndProof(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration,\n bytes32[] calldata _merkleProof\n ) public returns (uint256 bidId) {\n require(\n commitments[_commitmentId].collateralTokenType ==\n CommitmentCollateralType.ERC721_MERKLE_PROOF ||\n commitments[_commitmentId].collateralTokenType ==\n CommitmentCollateralType.ERC1155_MERKLE_PROOF,\n \"Invalid commitment collateral type\"\n );\n\n bytes32 _merkleRoot = bytes32(\n commitments[_commitmentId].collateralTokenId\n );\n bytes32 _leaf = keccak256(abi.encodePacked(_collateralTokenId));\n\n //make sure collateral token id is a leaf within the proof\n require(\n MerkleProofUpgradeable.verifyCalldata(\n _merkleProof,\n _merkleRoot,\n _leaf\n ),\n \"Invalid proof\"\n );\n\n return\n _acceptCommitment(\n _commitmentId,\n _principalAmount,\n _collateralAmount,\n _collateralTokenId,\n _collateralTokenAddress,\n _recipient,\n _interestRate,\n _loanDuration\n );\n }\n\n function acceptCommitmentWithProof(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n uint16 _interestRate,\n uint32 _loanDuration,\n bytes32[] calldata _merkleProof\n ) public returns (uint256 bidId) {\n return\n acceptCommitmentWithRecipientAndProof(\n _commitmentId,\n _principalAmount,\n _collateralAmount,\n _collateralTokenId,\n _collateralTokenAddress,\n address(0),\n _interestRate,\n _loanDuration,\n _merkleProof\n );\n }\n\n /**\n * @notice Accept the commitment to submitBid and acceptBid using the funds\n * @dev LoanDuration must be longer than the market payment cycle\n * @param _commitmentId The id of the commitment being accepted.\n * @param _principalAmount The amount of currency to borrow for the loan.\n * @param _collateralAmount The amount of collateral to use for the loan.\n * @param _collateralTokenId The tokenId of collateral to use for the loan if ERC721 or ERC1155.\n * @param _collateralTokenAddress The contract address to use for the loan collateral tokens.\n * @param _recipient The address to receive the loan funds.\n * @param _interestRate The interest rate APY to use for the loan in basis points.\n * @param _loanDuration The overall duration for the loan. Must be longer than market payment cycle duration.\n * @return bidId The ID of the loan that was created on TellerV2\n */\n function _acceptCommitment(\n uint256 _commitmentId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration\n ) internal returns (uint256 bidId) {\n Commitment storage commitment = commitments[_commitmentId];\n\n //make sure the commitment data adheres to required specifications and limits\n validateCommitment(commitment);\n\n //the collateral token of the commitment should be the same as the acceptor expects\n require(\n _collateralTokenAddress == commitment.collateralTokenAddress,\n \"Mismatching collateral token\"\n );\n\n //the interest rate must be at least as high has the commitment demands. The borrower can use a higher interest rate although that would not be beneficial to the borrower.\n require(\n _interestRate >= commitment.minInterestRate,\n \"Invalid interest rate\"\n );\n //the loan duration must be less than the commitment max loan duration. The lender who made the commitment expects the money to be returned before this window.\n require(\n _loanDuration <= commitment.maxDuration,\n \"Invalid loan max duration\"\n );\n\n require(\n commitmentPrincipalAccepted[_commitmentId] <= commitment.maxPrincipal,\n \"Invalid loan max principal\"\n );\n\n require(\n commitmentBorrowersList[_commitmentId].length() == 0 ||\n commitmentBorrowersList[_commitmentId].contains(_msgSender()),\n \"unauthorized commitment borrower\"\n );\n\n\n //require that the borrower accepting the commitment cannot borrow more than the commitments max principal\n if (_principalAmount > commitment.maxPrincipal) {\n revert InsufficientCommitmentAllocation({\n allocated: commitment.maxPrincipal,\n requested: _principalAmount\n });\n }\n\n {\n uint256 poolOraclePrice = UniswapPricingLibraryV2.getUniswapPriceRatioForPoolRoutes(\n commitmentUniswapPoolRoutes[_commitmentId]\n );\n\n // bool usePoolRoutes = commitmentUniswapPoolRoutes[_commitmentId] .length > 0;\n\n //use the worst case ratio either the oracle or the static ratio\n uint256 maxPrincipalPerCollateralAmount = (commitmentUniswapPoolRoutes[_commitmentId] .length > 0) // usePoolRoutes\n ? Math.min(\n poolOraclePrice .percent(commitmentPoolOracleLtvRatio[_commitmentId]) ,\n commitment.maxPrincipalPerCollateralAmount\n )\n : commitment.maxPrincipalPerCollateralAmount;\n\n uint256 requiredCollateral = getRequiredCollateral(\n _principalAmount,\n maxPrincipalPerCollateralAmount,\n commitment.collateralTokenType\n );\n\n if (_collateralAmount < requiredCollateral) {\n revert InsufficientBorrowerCollateral({\n required: requiredCollateral,\n actual: _collateralAmount\n });\n }\n }\n\n //ERC721 assets must have a quantity of 1\n if (\n commitment.collateralTokenType == CommitmentCollateralType.ERC721 ||\n commitment.collateralTokenType ==\n CommitmentCollateralType.ERC721_ANY_ID ||\n commitment.collateralTokenType ==\n CommitmentCollateralType.ERC721_MERKLE_PROOF\n ) {\n require(\n _collateralAmount == 1,\n \"invalid commitment collateral amount for ERC721\"\n );\n }\n\n //ERC721 and ERC1155 types strictly enforce a specific token Id. ERC721_ANY and ERC1155_ANY do not.\n if (\n commitment.collateralTokenType == CommitmentCollateralType.ERC721 ||\n commitment.collateralTokenType == CommitmentCollateralType.ERC1155\n ) {\n require(\n commitment.collateralTokenId == _collateralTokenId,\n \"invalid commitment collateral tokenId\"\n );\n }\n\n commitmentPrincipalAccepted[_commitmentId] += _principalAmount;\n\n require(\n commitmentPrincipalAccepted[_commitmentId] <=\n commitment.maxPrincipal,\n \"Exceeds max principal of commitment\"\n );\n\n CreateLoanArgs memory createLoanArgs;\n createLoanArgs.marketId = commitment.marketId;\n createLoanArgs.lendingToken = commitment.principalTokenAddress;\n createLoanArgs.principal = _principalAmount;\n createLoanArgs.duration = _loanDuration;\n createLoanArgs.interestRate = _interestRate;\n createLoanArgs.recipient = _recipient;\n if (commitment.collateralTokenType != CommitmentCollateralType.NONE) {\n createLoanArgs.collateral = new Collateral[](1);\n createLoanArgs.collateral[0] = Collateral({\n _collateralType: _getEscrowCollateralType(\n commitment.collateralTokenType\n ),\n _tokenId: _collateralTokenId,\n _amount: _collateralAmount,\n _collateralAddress: commitment.collateralTokenAddress\n });\n }\n\n bidId = _submitBidWithCollateral(createLoanArgs, _msgSender());\n\n _acceptBid(bidId, commitment.lender);\n\n emit ExercisedCommitment(\n _commitmentId,\n _msgSender(),\n _principalAmount,\n bidId\n );\n }\n\n /**\n * @notice Calculate the amount of collateral required to borrow a loan with _principalAmount of principal\n * @param _principalAmount The amount of currency to borrow for the loan.\n * @param _maxPrincipalPerCollateralAmount The ratio for the amount of principal that can be borrowed for each amount of collateral. \n * @param _collateralTokenType The type of collateral for the loan either ERC20, ERC721, ERC1155, or None.\n \n */\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount,\n CommitmentCollateralType _collateralTokenType\n ) public view virtual returns (uint256) {\n if (_collateralTokenType == CommitmentCollateralType.NONE) {\n return 0;\n }\n\n if (_collateralTokenType == CommitmentCollateralType.ERC20) {\n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n STANDARD_EXPANSION_FACTOR,\n _maxPrincipalPerCollateralAmount,\n MathUpgradeable.Rounding.Up\n );\n }\n\n //for NFTs, do not use the uniswap expansion factor \n return\n MathUpgradeable.mulDiv(\n _principalAmount,\n 1,\n _maxPrincipalPerCollateralAmount,\n MathUpgradeable.Rounding.Up\n );\n\n \n }\n\n /**\n * @dev Returns the PoolRouteConfig at a specific index for a given commitmentId from the commitmentUniswapPoolRoutes mapping.\n * @param commitmentId The commitmentId to access the mapping.\n * @param index The index in the array of PoolRouteConfigs for the given commitmentId.\n * @return The PoolRouteConfig at the specified index.\n */\n function getCommitmentUniswapPoolRoute(uint256 commitmentId, uint index)\n public\n view\n returns (IUniswapPricingLibrary.PoolRouteConfig memory)\n {\n require(\n index < commitmentUniswapPoolRoutes[commitmentId].length,\n \"Index out of bounds\"\n );\n return commitmentUniswapPoolRoutes[commitmentId][index];\n }\n\n /**\n * @dev Returns the entire array of PoolRouteConfigs for a given commitmentId from the commitmentUniswapPoolRoutes mapping.\n * @param commitmentId The commitmentId to access the mapping.\n * @return The entire array of PoolRouteConfigs for the specified commitmentId.\n */\n function getAllCommitmentUniswapPoolRoutes(uint256 commitmentId)\n public\n view\n returns (IUniswapPricingLibrary.PoolRouteConfig[] memory)\n {\n return commitmentUniswapPoolRoutes[commitmentId];\n }\n\n /**\n * @dev Returns the uint16 value for a given commitmentId from the commitmentPoolOracleLtvRatio mapping.\n * @param commitmentId The key to access the mapping.\n * @return The uint16 value for the specified commitmentId.\n */\n function getCommitmentPoolOracleLtvRatio(uint256 commitmentId)\n public\n view\n returns (uint16)\n {\n return commitmentPoolOracleLtvRatio[commitmentId];\n }\n\n // ---- TWAP\n\n function getUniswapV3PoolAddress(\n address _principalTokenAddress,\n address _collateralTokenAddress,\n uint24 _uniswapPoolFee\n ) public view returns (address) {\n return\n IUniswapV3Factory(UNISWAP_V3_FACTORY).getPool(\n _principalTokenAddress,\n _collateralTokenAddress,\n _uniswapPoolFee\n );\n }\n \n\n function getSqrtTwapX96(address uniswapV3Pool, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n if (twapInterval == 0) {\n // return the current price if twapInterval == 0\n (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0();\n } else {\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = twapInterval + 1; // from (before)\n secondsAgos[1] = 1; // one block prior\n\n (int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapV3Pool)\n .observe(secondsAgos);\n\n // tick(imprecise as it's an integer) to price\n sqrtPriceX96 = TickMath.getSqrtRatioAtTick(\n int24(\n (tickCumulatives[1] - tickCumulatives[0]) /\n int32(twapInterval)\n )\n );\n }\n }\n\n function getPriceX96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceX96)\n {\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96);\n }\n\n // -----\n\n /**\n * @notice Return the array of borrowers that are allowlisted for a commitment\n * @param _commitmentId The commitment id for the commitment to query.\n * @return borrowers_ An array of addresses restricted to accept the commitment. Empty array means unrestricted.\n */\n function getCommitmentBorrowers(uint256 _commitmentId)\n external\n view\n returns (address[] memory borrowers_)\n {\n borrowers_ = commitmentBorrowersList[_commitmentId].values();\n }\n\n /**\n * @notice Return the collateral type based on the commitmentcollateral type. Collateral type is used in the base lending protocol.\n * @param _type The type of collateral to be used for the loan.\n */\n function _getEscrowCollateralType(CommitmentCollateralType _type)\n internal\n pure\n returns (CollateralType)\n {\n if (_type == CommitmentCollateralType.ERC20) {\n return CollateralType.ERC20;\n }\n if (\n _type == CommitmentCollateralType.ERC721 ||\n _type == CommitmentCollateralType.ERC721_ANY_ID ||\n _type == CommitmentCollateralType.ERC721_MERKLE_PROOF\n ) {\n return CollateralType.ERC721;\n }\n if (\n _type == CommitmentCollateralType.ERC1155 ||\n _type == CommitmentCollateralType.ERC1155_ANY_ID ||\n _type == CommitmentCollateralType.ERC1155_MERKLE_PROOF\n ) {\n return CollateralType.ERC1155;\n }\n\n revert(\"Unknown Collateral Type\");\n }\n\n function getCommitmentMarketId(uint256 _commitmentId)\n external\n view\n returns (uint256)\n {\n return commitments[_commitmentId].marketId;\n }\n\n function getCommitmentLender(uint256 _commitmentId)\n external\n view\n returns (address)\n {\n return commitments[_commitmentId].lender;\n }\n\n function getCommitmentAcceptedPrincipal(uint256 _commitmentId)\n external\n view\n returns (uint256)\n {\n return commitmentPrincipalAccepted[_commitmentId];\n }\n\n function getCommitmentMaxPrincipal(uint256 _commitmentId)\n external\n view\n returns (uint256)\n {\n return commitments[_commitmentId].maxPrincipal;\n }\n\n function getCommitmentPrincipalTokenAddress(uint256 _commitmentId)\n external\n view\n returns (address)\n {\n return commitments[_commitmentId].principalTokenAddress;\n }\n\n function getCommitmentCollateralTokenAddress(uint256 _commitmentId)\n external\n view\n returns (address)\n {\n return commitments[_commitmentId].collateralTokenAddress;\n }\n\n\n\n //Overrides\n function _msgSender()\n internal\n view\n virtual\n override(ContextUpgradeable, ExtensionsContextUpgradeable)\n returns (address sender)\n {\n return ExtensionsContextUpgradeable._msgSender();\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/LenderCommitmentForwarderV2.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"./LenderCommitmentForwarder_U2.sol\";\n\ncontract LenderCommitmentForwarderV2 is LenderCommitmentForwarder_U2 {\n constructor(\n address _tellerV2,\n address _marketRegistry,\n address _uniswapV3Factory\n )\n LenderCommitmentForwarder_U2(\n _tellerV2,\n _marketRegistry,\n _uniswapV3Factory\n )\n {\n // we only want this on an proxy deployment so it only affects the impl\n _disableInitializers();\n }\n}\n" + }, + "contracts/LenderCommitmentForwarder/LoanReferralForwarder.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n// Interfaces\nimport \"../interfaces/ITellerV2.sol\";\nimport \"../interfaces/IProtocolFee.sol\";\nimport \"../interfaces/ITellerV2Storage.sol\";\nimport \"../interfaces/IMarketRegistry.sol\"; \nimport \"../interfaces/ISmartCommitment.sol\";\nimport \"../interfaces/ISmartCommitmentForwarder.sol\";\nimport \"../interfaces/IFlashRolloverLoan_G4.sol\";\nimport \"../libraries/NumbersLib.sol\";\n\nimport { ILenderCommitmentForwarder } from \"../interfaces/ILenderCommitmentForwarder.sol\";\n \nimport { ILenderCommitmentForwarder_U1 } from \"../interfaces/ILenderCommitmentForwarder_U1.sol\";\n\n\n\n\ncontract LoanReferralForwarder \n {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n ITellerV2 public immutable TELLER_V2;\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n \n \n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n address smartCommitmentAddress; //if this is not address(0), we will use this ! leave empty if not used. \n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n bytes32[] merkleProof; //empty array if not used\n }\n\n\n event CommitmentAcceptedWithReferral(\n uint256 indexed bidId,\n address indexed recipient,\n uint256 fundsRemaining,\n uint256 reward,\n address rewardRecipient\n );\n\n /**\n *\n * @notice Initializes the FlashRolloverLoan with necessary contract addresses.\n *\n * @dev Using a custom OpenZeppelin upgrades tag. Ensure the constructor logic is safe for upgrades.\n *\n * @param _tellerV2 The address of the TellerV2 contract.\n \n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _tellerV2 \n \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n \n }\n\n \n\n /*\n \n */\n function acceptCommitmentWithReferral(\n address _commitmentForwarder, //leave 0 if using smart commitment address\n \n \n AcceptCommitmentArgs calldata _acceptCommitmentArgs ,\n \n \n address _recipient,\n uint256 _reward,\n address _rewardRecipient\n\n ) external returns (uint256 bidId_) {\n\n \n address principalTokenAddress = address(0);\n uint256 balanceBefore;\n\n \n require(_reward <= _acceptCommitmentArgs.principalAmount / 10, \"Reward can be no more than 10% of principal\");\n\n if (_acceptCommitmentArgs.smartCommitmentAddress != address(0)) {\n\n \n principalTokenAddress = ISmartCommitment(_acceptCommitmentArgs.smartCommitmentAddress).getPrincipalTokenAddress ();\n \n // Accept commitment and receive funds to this contract\n balanceBefore = IERC20(principalTokenAddress).balanceOf(address(this));\n \n bidId_ = _acceptSmartCommitmentWithRecipient(\n _commitmentForwarder,\n _acceptCommitmentArgs\n\n );\n\n \n }else{ \n principalTokenAddress = ILenderCommitmentForwarder_U1(_commitmentForwarder)\n .getCommitmentPrincipalTokenAddress (_acceptCommitmentArgs.commitmentId);\n \n // Accept commitment and receive funds to this contract\n balanceBefore = IERC20(principalTokenAddress).balanceOf(address(this));\n \n\n bidId_ = _acceptCommitmentWithRecipient(\n _commitmentForwarder,\n _acceptCommitmentArgs\n\n ); \n\n\n\n }\n \n uint256 balanceAfter = IERC20(principalTokenAddress).balanceOf(address(this));\n\n uint256 fundsRemaining = balanceAfter - balanceBefore;\n\n // require( fundsRemaining >= _minAmountReceived, \"Insufficient funds received\" );\n\n \n IERC20Upgradeable(principalTokenAddress).transfer(\n _rewardRecipient,\n _reward\n );\n\n IERC20Upgradeable(principalTokenAddress).transfer(\n _recipient,\n fundsRemaining - _reward\n );\n\n\n emit CommitmentAcceptedWithReferral(bidId_, _recipient, fundsRemaining, _reward, _rewardRecipient);\n \n \n }\n\n\n function _acceptSmartCommitmentWithRecipient( \n address _smartCommitmentForwarder,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs \n \n\n ) internal returns (uint256 bidId_) {\n\n bytes memory responseData = address(_smartCommitmentForwarder)\n .functionCall(\n abi.encodePacked(\n abi.encodeWithSelector(\n ISmartCommitmentForwarder\n .acceptSmartCommitmentWithRecipient\n .selector,\n _acceptCommitmentArgs.smartCommitmentAddress,\n _acceptCommitmentArgs.principalAmount,\n _acceptCommitmentArgs.collateralAmount,\n _acceptCommitmentArgs.collateralTokenId,\n _acceptCommitmentArgs.collateralTokenAddress,\n address(this),\n _acceptCommitmentArgs.interestRate,\n _acceptCommitmentArgs.loanDuration\n ),\n msg.sender // borrower \n )\n );\n\n\n (bidId_) = abi.decode(responseData, (uint256));\n\n\n\n }\n\n\n\n function _acceptCommitmentWithRecipient(\n address _commitmentForwarder,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs \n \n\n ) internal returns (uint256 bidId_) {\n\n bytes memory responseData = address(_commitmentForwarder)\n .functionCall(\n abi.encodePacked(\n abi.encodeWithSelector(\n ILenderCommitmentForwarder\n .acceptCommitmentWithRecipient\n .selector,\n _acceptCommitmentArgs.commitmentId,\n _acceptCommitmentArgs.principalAmount,\n _acceptCommitmentArgs.collateralAmount,\n _acceptCommitmentArgs.collateralTokenId,\n _acceptCommitmentArgs.collateralTokenAddress,\n address(this),\n _acceptCommitmentArgs.interestRate,\n _acceptCommitmentArgs.loanDuration\n ),\n msg.sender //borrower \n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\n\n\n }\n\n \n /**\n * @notice Fetches the protocol fee percentage from the Teller V2 protocol.\n * @return The protocol fee percentage as defined in the Teller V2 protocol.\n */\n function _getProtocolFeePct() internal view returns (uint16) {\n return IProtocolFee(address(TELLER_V2)).protocolFee();\n }\n}" + }, + "contracts/LenderCommitmentForwarder/LoanReferralForwarderV2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Contracts\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n// Interfaces\nimport \"../interfaces/ITellerV2.sol\";\nimport \"../interfaces/IProtocolFee.sol\";\nimport \"../interfaces/ITellerV2Storage.sol\";\nimport \"../interfaces/IMarketRegistry.sol\"; \nimport \"../interfaces/ISmartCommitment.sol\";\nimport \"../interfaces/ISmartCommitmentForwarder.sol\";\nimport \"../interfaces/IFlashRolloverLoan_G4.sol\";\nimport \"../libraries/NumbersLib.sol\";\n\nimport { ILenderCommitmentForwarder } from \"../interfaces/ILenderCommitmentForwarder.sol\";\n \nimport { ILenderCommitmentForwarder_U1 } from \"../interfaces/ILenderCommitmentForwarder_U1.sol\";\n\nimport '../libraries/uniswap/periphery/libraries/TransferHelper.sol';\n\n\ncontract LoanReferralForwarderV2 \n {\n using AddressUpgradeable for address;\n using NumbersLib for uint256;\n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n ITellerV2 public immutable TELLER_V2;\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n \n \n\n struct AcceptCommitmentArgs {\n uint256 commitmentId;\n address smartCommitmentAddress; //if this is not address(0), we will use this ! leave empty if not used. \n uint256 principalAmount;\n uint256 collateralAmount;\n uint256 collateralTokenId;\n address collateralTokenAddress;\n uint16 interestRate;\n uint32 loanDuration;\n bytes32[] merkleProof; //empty array if not used\n }\n\n\n event CommitmentAcceptedWithReward(\n uint256 indexed bidId,\n address indexed recipient,\n address principalTokenAddress, \n uint256 fundsRemaining,\n uint256 reward,\n address rewardRecipient,\n uint256 atmId \n );\n\n \n constructor(\n address _tellerV2 \n \n ) {\n TELLER_V2 = ITellerV2(_tellerV2);\n \n }\n\n \n\n /*\n \n */\n function acceptCommitmentWithReferral(\n address _commitmentForwarder, \n \n AcceptCommitmentArgs calldata _acceptCommitmentArgs ,\n \n uint256 _atmId, \n address _recipient,\n uint256 _reward,\n address _rewardRecipient\n\n ) external returns (uint256 bidId_) {\n\n \n address principalTokenAddress = address(0);\n uint256 balanceBefore;\n\n \n require(_reward <= _acceptCommitmentArgs.principalAmount / 10, \"Reward can be no more than 10% of principal\");\n\n if (_acceptCommitmentArgs.smartCommitmentAddress != address(0)) {\n\n \n principalTokenAddress = ISmartCommitment(_acceptCommitmentArgs.smartCommitmentAddress).getPrincipalTokenAddress ();\n \n // Accept commitment and receive funds to this contract\n balanceBefore = IERC20(principalTokenAddress).balanceOf(address(this));\n \n bidId_ = _acceptSmartCommitmentWithRecipient(\n _commitmentForwarder,\n _acceptCommitmentArgs\n\n );\n\n \n }else{ \n principalTokenAddress = ILenderCommitmentForwarder_U1(_commitmentForwarder)\n .getCommitmentPrincipalTokenAddress (_acceptCommitmentArgs.commitmentId);\n \n // Accept commitment and receive funds to this contract\n balanceBefore = IERC20(principalTokenAddress).balanceOf(address(this));\n \n\n bidId_ = _acceptCommitmentWithRecipient(\n _commitmentForwarder,\n _acceptCommitmentArgs\n\n ); \n\n\n\n }\n \n uint256 balanceAfter = IERC20(principalTokenAddress).balanceOf(address(this));\n\n uint256 fundsRemaining = balanceAfter - balanceBefore;\n \n\n if (_reward > 0) {\n\n TransferHelper.safeTransferFrom(principalTokenAddress, address(this), _rewardRecipient, _reward); \n\n \n }\n\n TransferHelper.safeTransferFrom(principalTokenAddress, address(this), _recipient, fundsRemaining - _reward); \n \n\n emit CommitmentAcceptedWithReward( bidId_, _recipient, principalTokenAddress, fundsRemaining, _reward, _rewardRecipient , _atmId);\n \n \n }\n\n\n function _acceptSmartCommitmentWithRecipient( \n address _smartCommitmentForwarder,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs \n \n\n ) internal returns (uint256 bidId_) {\n\n bytes memory responseData = address(_smartCommitmentForwarder)\n .functionCall(\n abi.encodePacked(\n abi.encodeWithSelector(\n ISmartCommitmentForwarder\n .acceptSmartCommitmentWithRecipient\n .selector,\n _acceptCommitmentArgs.smartCommitmentAddress,\n _acceptCommitmentArgs.principalAmount,\n _acceptCommitmentArgs.collateralAmount,\n _acceptCommitmentArgs.collateralTokenId,\n _acceptCommitmentArgs.collateralTokenAddress,\n address(this),\n _acceptCommitmentArgs.interestRate,\n _acceptCommitmentArgs.loanDuration\n ),\n msg.sender // borrower \n )\n );\n\n\n (bidId_) = abi.decode(responseData, (uint256));\n\n\n\n }\n\n\n\n function _acceptCommitmentWithRecipient(\n address _commitmentForwarder,\n AcceptCommitmentArgs calldata _acceptCommitmentArgs \n \n\n ) internal returns (uint256 bidId_) {\n\n bytes memory responseData = address(_commitmentForwarder)\n .functionCall(\n abi.encodePacked(\n abi.encodeWithSelector(\n ILenderCommitmentForwarder\n .acceptCommitmentWithRecipient\n .selector,\n _acceptCommitmentArgs.commitmentId,\n _acceptCommitmentArgs.principalAmount,\n _acceptCommitmentArgs.collateralAmount,\n _acceptCommitmentArgs.collateralTokenId,\n _acceptCommitmentArgs.collateralTokenAddress,\n address(this),\n _acceptCommitmentArgs.interestRate,\n _acceptCommitmentArgs.loanDuration\n ),\n msg.sender //borrower \n )\n );\n\n (bidId_) = abi.decode(responseData, (uint256));\n\n\n }\n\n \n /**\n * @notice Fetches the protocol fee percentage from the Teller V2 protocol.\n * @return The protocol fee percentage as defined in the Teller V2 protocol.\n */\n function _getProtocolFeePct() internal view returns (uint16) {\n return IProtocolFee(address(TELLER_V2)).protocolFee();\n }\n}" + }, + "contracts/LenderCommitmentForwarder/SmartCommitmentForwarder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../TellerV2MarketForwarder_G3.sol\";\nimport \"./extensions/ExtensionsContextUpgradeable.sol\";\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"../interfaces/ISmartCommitmentForwarder.sol\";\nimport \"./LenderCommitmentForwarder_G1.sol\";\n\nimport \"../interfaces/IPausableTimestamp.sol\";\n\nimport \"../interfaces/IHasProtocolPausingManager.sol\";\n\nimport \"../interfaces/IProtocolPausingManager.sol\";\n\nimport \"../oracleprotection/OracleProtectionManager.sol\";\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\n\n\nimport \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\n\nimport { CommitmentCollateralType, ISmartCommitment } from \"../interfaces/ISmartCommitment.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n\n/* \nThe smart commitment forwarder is the central hub for activity related to Lender Group Pools, also knnown as SmartCommitments.\n\nUsers of teller protocol can set this contract as a TrustedForwarder to allow it to conduct lending activity on their behalf.\n\nUsers can also approve Extensions, such as Rollover, which will allow the extension to conduct loans on the users behalf through this forwarder by way of overrides to _msgSender() using the last 20 bytes of delegatecall. \n\n\nROLES \n\n \n The protocol owner can modify the liquidation fee percent , call setOracle and setIsStrictMode\n\n Any protocol pauser can pause and unpause this contract \n\n Anyone can call registerOracle to register a contract for use (firewall access)\n\n\n\n*/\n \ncontract SmartCommitmentForwarder is\n ExtensionsContextUpgradeable, //this should always be first for upgradeability\n TellerV2MarketForwarder_G3,\n PausableUpgradeable, //this does add some storage but AFTER all other storage\n ReentrancyGuardUpgradeable, //adds many storage slots so breaks upgradeability \n OwnableUpgradeable, //deprecated\n OracleProtectionManager, //uses deterministic storage slots \n ISmartCommitmentForwarder,\n IPausableTimestamp\n {\n\n using MathUpgradeable for uint256;\n\n event ExercisedSmartCommitment(\n address indexed smartCommitmentAddress,\n address borrower,\n uint256 tokenAmount,\n uint256 bidId\n );\n\n error InsufficientBorrowerCollateral(uint256 required, uint256 actual);\n\n\n\n modifier onlyProtocolPauser() { \n\n address pausingManager = IHasProtocolPausingManager( _tellerV2 ).getProtocolPausingManager();\n require( IProtocolPausingManager( pausingManager ).isPauser(_msgSender()) , \"Sender not authorized\");\n _;\n }\n\n\n modifier onlyProtocolOwner() { \n require( Ownable( _tellerV2 ).owner() == _msgSender() , \"Sender not authorized\");\n _;\n }\n\n uint256 public liquidationProtocolFeePercent; \n uint256 internal lastUnpausedAt;\n\n\n constructor(address _protocolAddress, address _marketRegistry)\n TellerV2MarketForwarder_G3(_protocolAddress, _marketRegistry)\n { }\n\n function initialize() public initializer { \n __Pausable_init();\n __Ownable_init_unchained();\n }\n \n\n function setLiquidationProtocolFeePercent(uint256 _percent) \n public onlyProtocolOwner { \n //max is 100% \n require( _percent <= 10000 , \"invalid fee percent\" );\n liquidationProtocolFeePercent = _percent;\n }\n\n function getLiquidationProtocolFeePercent() \n public view returns (uint256){ \n return liquidationProtocolFeePercent ;\n }\n\n /**\n * @notice Accept the commitment to submitBid and acceptBid using the funds\n * @dev LoanDuration must be longer than the market payment cycle\n * @param _smartCommitmentAddress The address of the smart commitment contract.\n * @param _principalAmount The amount of currency to borrow for the loan.\n * @param _collateralAmount The amount of collateral to use for the loan.\n * @param _collateralTokenId The tokenId of collateral to use for the loan if ERC721 or ERC1155.\n * @param _collateralTokenAddress The contract address to use for the loan collateral tokens.\n * @param _recipient The address to receive the loan funds.\n * @param _interestRate The interest rate APY to use for the loan in basis points.\n * @param _loanDuration The overall duration for the loan. Must be longer than market payment cycle duration.\n * @return bidId The ID of the loan that was created on TellerV2\n */\n function acceptSmartCommitmentWithRecipient(\n address _smartCommitmentAddress,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration\n ) public whenNotPaused nonReentrant returns (uint256 bidId) {\n require(\n ISmartCommitment(_smartCommitmentAddress)\n .getCollateralTokenType() <=\n CommitmentCollateralType.ERC1155_ANY_ID,\n \"Invalid commitment collateral type\"\n );\n\n return\n _acceptCommitment(\n _smartCommitmentAddress,\n _principalAmount,\n _collateralAmount,\n _collateralTokenId,\n _collateralTokenAddress,\n _recipient,\n _interestRate,\n _loanDuration\n );\n }\n\n function _acceptCommitment(\n address _smartCommitmentAddress,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n uint256 _collateralTokenId,\n address _collateralTokenAddress,\n address _recipient,\n uint16 _interestRate,\n uint32 _loanDuration\n ) internal returns (uint256 bidId) {\n ISmartCommitment _commitment = ISmartCommitment(\n _smartCommitmentAddress\n );\n\n CreateLoanArgs memory createLoanArgs;\n\n createLoanArgs.marketId = _commitment.getMarketId();\n createLoanArgs.lendingToken = _commitment.getPrincipalTokenAddress();\n createLoanArgs.principal = _principalAmount;\n createLoanArgs.duration = _loanDuration;\n createLoanArgs.interestRate = _interestRate;\n createLoanArgs.recipient = _recipient;\n\n CommitmentCollateralType commitmentCollateralTokenType = _commitment\n .getCollateralTokenType();\n\n if (commitmentCollateralTokenType != CommitmentCollateralType.NONE) {\n createLoanArgs.collateral = new Collateral[](1);\n createLoanArgs.collateral[0] = Collateral({\n _collateralType: _getEscrowCollateralType(\n commitmentCollateralTokenType\n ),\n _tokenId: _collateralTokenId,\n _amount: _collateralAmount,\n _collateralAddress: _collateralTokenAddress // commitment.collateralTokenAddress\n });\n }\n\n bidId = _submitBidWithCollateral(createLoanArgs, _msgSender());\n\n _commitment.acceptFundsForAcceptBid(\n _msgSender(), //borrower\n bidId,\n _principalAmount,\n _collateralAmount,\n _collateralTokenAddress,\n _collateralTokenId,\n _loanDuration,\n _interestRate\n );\n\n emit ExercisedSmartCommitment(\n _smartCommitmentAddress,\n _msgSender(),\n _principalAmount,\n bidId\n );\n }\n\n /**\n * @notice Return the collateral type based on the commitmentcollateral type. Collateral type is used in the base lending protocol.\n * @param _type The type of collateral to be used for the loan.\n */\n function _getEscrowCollateralType(CommitmentCollateralType _type)\n internal\n pure\n returns (CollateralType)\n {\n if (_type == CommitmentCollateralType.ERC20) {\n return CollateralType.ERC20;\n }\n if (\n _type == CommitmentCollateralType.ERC721 ||\n _type == CommitmentCollateralType.ERC721_ANY_ID ||\n _type == CommitmentCollateralType.ERC721_MERKLE_PROOF\n ) {\n return CollateralType.ERC721;\n }\n if (\n _type == CommitmentCollateralType.ERC1155 ||\n _type == CommitmentCollateralType.ERC1155_ANY_ID ||\n _type == CommitmentCollateralType.ERC1155_MERKLE_PROOF\n ) {\n return CollateralType.ERC1155;\n }\n\n revert(\"Unknown Collateral Type\");\n }\n\n\n\n /**\n * @notice Lets the DAO/owner of the protocol implement an emergency stop mechanism.\n */\n function pause() public virtual onlyProtocolPauser whenNotPaused {\n _pause();\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol undo a previously implemented emergency stop.\n */\n function unpause() public virtual onlyProtocolPauser whenPaused {\n setLastUnpausedAt();\n _unpause();\n }\n\n\n function getLastUnpausedAt() \n public view \n returns (uint256) {\n\n address pausingManager = IHasProtocolPausingManager( _tellerV2 ).getProtocolPausingManager();\n \n return MathUpgradeable.max(\n lastUnpausedAt,\n IPausableTimestamp(pausingManager).getLastUnpausedAt()\n );\n\n }\n\n\n function setLastUnpausedAt() internal {\n lastUnpausedAt = block.timestamp;\n }\n\n\n function setOracle(address _oracle) external onlyProtocolOwner {\n _setOracle(_oracle);\n } \n\n function setIsStrictMode(bool _mode) external onlyProtocolOwner {\n _setIsStrictMode(_mode);\n } \n\n\n // -----\n\n //Overrides\n function _msgSender()\n internal\n view\n virtual\n override(ContextUpgradeable, ExtensionsContextUpgradeable)\n returns (address sender)\n {\n return ExtensionsContextUpgradeable._msgSender();\n }\n \n}\n" + }, + "contracts/libraries/DateTimeLib.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.0 <0.9.0;\n\n// ----------------------------------------------------------------------------\n// BokkyPooBah's DateTime Library v1.01\n//\n// A gas-efficient Solidity date and time library\n//\n// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary\n//\n// Tested date range 1970/01/01 to 2345/12/31\n//\n// Conventions:\n// Unit | Range | Notes\n// :-------- |:-------------:|:-----\n// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC\n// year | 1970 ... 2345 |\n// month | 1 ... 12 |\n// day | 1 ... 31 |\n// hour | 0 ... 23 |\n// minute | 0 ... 59 |\n// second | 0 ... 59 |\n// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday\n//\n//\n// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.\n// ----------------------------------------------------------------------------\n\nlibrary BokkyPooBahsDateTimeLibrary {\n uint constant SECONDS_PER_DAY = 24 * 60 * 60;\n uint constant SECONDS_PER_HOUR = 60 * 60;\n uint constant SECONDS_PER_MINUTE = 60;\n int constant OFFSET19700101 = 2440588;\n\n uint constant DOW_MON = 1;\n uint constant DOW_TUE = 2;\n uint constant DOW_WED = 3;\n uint constant DOW_THU = 4;\n uint constant DOW_FRI = 5;\n uint constant DOW_SAT = 6;\n uint constant DOW_SUN = 7;\n\n // ------------------------------------------------------------------------\n // Calculate the number of days from 1970/01/01 to year/month/day using\n // the date conversion algorithm from\n // https://aa.usno.navy.mil/faq/JD_formula.html\n // and subtracting the offset 2440588 so that 1970/01/01 is day 0\n //\n // days = day\n // - 32075\n // + 1461 * (year + 4800 + (month - 14) / 12) / 4\n // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12\n // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4\n // - offset\n // ------------------------------------------------------------------------\n function _daysFromDate(uint year, uint month, uint day)\n internal\n pure\n returns (uint _days)\n {\n require(year >= 1970);\n int _year = int(year);\n int _month = int(month);\n int _day = int(day);\n\n int __days = _day -\n 32075 +\n (1461 * (_year + 4800 + (_month - 14) / 12)) /\n 4 +\n (367 * (_month - 2 - ((_month - 14) / 12) * 12)) /\n 12 -\n (3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /\n 4 -\n OFFSET19700101;\n\n _days = uint(__days);\n }\n\n // ------------------------------------------------------------------------\n // Calculate year/month/day from the number of days since 1970/01/01 using\n // the date conversion algorithm from\n // http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n // and adding the offset 2440588 so that 1970/01/01 is day 0\n //\n // int L = days + 68569 + offset\n // int N = 4 * L / 146097\n // L = L - (146097 * N + 3) / 4\n // year = 4000 * (L + 1) / 1461001\n // L = L - 1461 * year / 4 + 31\n // month = 80 * L / 2447\n // dd = L - 2447 * month / 80\n // L = month / 11\n // month = month + 2 - 12 * L\n // year = 100 * (N - 49) + year + L\n // ------------------------------------------------------------------------\n function _daysToDate(uint _days)\n internal\n pure\n returns (uint year, uint month, uint day)\n {\n int __days = int(_days);\n\n int L = __days + 68569 + OFFSET19700101;\n int N = (4 * L) / 146097;\n L = L - (146097 * N + 3) / 4;\n int _year = (4000 * (L + 1)) / 1461001;\n L = L - (1461 * _year) / 4 + 31;\n int _month = (80 * L) / 2447;\n int _day = L - (2447 * _month) / 80;\n L = _month / 11;\n _month = _month + 2 - 12 * L;\n _year = 100 * (N - 49) + _year + L;\n\n year = uint(_year);\n month = uint(_month);\n day = uint(_day);\n }\n\n function timestampFromDate(uint year, uint month, uint day)\n internal\n pure\n returns (uint timestamp)\n {\n timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;\n }\n\n function timestampFromDateTime(\n uint year,\n uint month,\n uint day,\n uint hour,\n uint minute,\n uint second\n ) internal pure returns (uint timestamp) {\n timestamp =\n _daysFromDate(year, month, day) *\n SECONDS_PER_DAY +\n hour *\n SECONDS_PER_HOUR +\n minute *\n SECONDS_PER_MINUTE +\n second;\n }\n\n function timestampToDate(uint timestamp)\n internal\n pure\n returns (uint year, uint month, uint day)\n {\n (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);\n }\n\n function timestampToDateTime(uint timestamp)\n internal\n pure\n returns (\n uint year,\n uint month,\n uint day,\n uint hour,\n uint minute,\n uint second\n )\n {\n (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);\n uint secs = timestamp % SECONDS_PER_DAY;\n hour = secs / SECONDS_PER_HOUR;\n secs = secs % SECONDS_PER_HOUR;\n minute = secs / SECONDS_PER_MINUTE;\n second = secs % SECONDS_PER_MINUTE;\n }\n\n function isValidDate(uint year, uint month, uint day)\n internal\n pure\n returns (bool valid)\n {\n if (year >= 1970 && month > 0 && month <= 12) {\n uint daysInMonth = _getDaysInMonth(year, month);\n if (day > 0 && day <= daysInMonth) {\n valid = true;\n }\n }\n }\n\n function isValidDateTime(\n uint year,\n uint month,\n uint day,\n uint hour,\n uint minute,\n uint second\n ) internal pure returns (bool valid) {\n if (isValidDate(year, month, day)) {\n if (hour < 24 && minute < 60 && second < 60) {\n valid = true;\n }\n }\n }\n\n function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {\n (uint year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY);\n leapYear = _isLeapYear(year);\n }\n\n function _isLeapYear(uint year) internal pure returns (bool leapYear) {\n leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);\n }\n\n function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {\n weekDay = getDayOfWeek(timestamp) <= DOW_FRI;\n }\n\n function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {\n weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;\n }\n\n function getDaysInMonth(uint timestamp)\n internal\n pure\n returns (uint daysInMonth)\n {\n (uint year, uint month, ) = _daysToDate(timestamp / SECONDS_PER_DAY);\n daysInMonth = _getDaysInMonth(year, month);\n }\n\n function _getDaysInMonth(uint year, uint month)\n internal\n pure\n returns (uint daysInMonth)\n {\n if (\n month == 1 ||\n month == 3 ||\n month == 5 ||\n month == 7 ||\n month == 8 ||\n month == 10 ||\n month == 12\n ) {\n daysInMonth = 31;\n } else if (month != 2) {\n daysInMonth = 30;\n } else {\n daysInMonth = _isLeapYear(year) ? 29 : 28;\n }\n }\n\n // 1 = Monday, 7 = Sunday\n function getDayOfWeek(uint timestamp)\n internal\n pure\n returns (uint dayOfWeek)\n {\n uint _days = timestamp / SECONDS_PER_DAY;\n dayOfWeek = ((_days + 3) % 7) + 1;\n }\n\n function getYear(uint timestamp) internal pure returns (uint year) {\n (year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY);\n }\n\n function getMonth(uint timestamp) internal pure returns (uint month) {\n (, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY);\n }\n\n function getDay(uint timestamp) internal pure returns (uint day) {\n (, , day) = _daysToDate(timestamp / SECONDS_PER_DAY);\n }\n\n function getHour(uint timestamp) internal pure returns (uint hour) {\n uint secs = timestamp % SECONDS_PER_DAY;\n hour = secs / SECONDS_PER_HOUR;\n }\n\n function getMinute(uint timestamp) internal pure returns (uint minute) {\n uint secs = timestamp % SECONDS_PER_HOUR;\n minute = secs / SECONDS_PER_MINUTE;\n }\n\n function getSecond(uint timestamp) internal pure returns (uint second) {\n second = timestamp % SECONDS_PER_MINUTE;\n }\n\n function addYears(uint timestamp, uint _years)\n internal\n pure\n returns (uint newTimestamp)\n {\n (uint year, uint month, uint day) = _daysToDate(\n timestamp / SECONDS_PER_DAY\n );\n year += _years;\n uint daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp =\n _daysFromDate(year, month, day) *\n SECONDS_PER_DAY +\n (timestamp % SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addMonths(uint timestamp, uint _months)\n internal\n pure\n returns (uint newTimestamp)\n {\n (uint year, uint month, uint day) = _daysToDate(\n timestamp / SECONDS_PER_DAY\n );\n month += _months;\n year += (month - 1) / 12;\n month = ((month - 1) % 12) + 1;\n uint daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp =\n _daysFromDate(year, month, day) *\n SECONDS_PER_DAY +\n (timestamp % SECONDS_PER_DAY);\n require(newTimestamp >= timestamp);\n }\n\n function addDays(uint timestamp, uint _days)\n internal\n pure\n returns (uint newTimestamp)\n {\n newTimestamp = timestamp + _days * SECONDS_PER_DAY;\n require(newTimestamp >= timestamp);\n }\n\n function addHours(uint timestamp, uint _hours)\n internal\n pure\n returns (uint newTimestamp)\n {\n newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;\n require(newTimestamp >= timestamp);\n }\n\n function addMinutes(uint timestamp, uint _minutes)\n internal\n pure\n returns (uint newTimestamp)\n {\n newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;\n require(newTimestamp >= timestamp);\n }\n\n function addSeconds(uint timestamp, uint _seconds)\n internal\n pure\n returns (uint newTimestamp)\n {\n newTimestamp = timestamp + _seconds;\n require(newTimestamp >= timestamp);\n }\n\n function subYears(uint timestamp, uint _years)\n internal\n pure\n returns (uint newTimestamp)\n {\n (uint year, uint month, uint day) = _daysToDate(\n timestamp / SECONDS_PER_DAY\n );\n year -= _years;\n uint daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp =\n _daysFromDate(year, month, day) *\n SECONDS_PER_DAY +\n (timestamp % SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subMonths(uint timestamp, uint _months)\n internal\n pure\n returns (uint newTimestamp)\n {\n (uint year, uint month, uint day) = _daysToDate(\n timestamp / SECONDS_PER_DAY\n );\n uint yearMonth = year * 12 + (month - 1) - _months;\n year = yearMonth / 12;\n month = (yearMonth % 12) + 1;\n uint daysInMonth = _getDaysInMonth(year, month);\n if (day > daysInMonth) {\n day = daysInMonth;\n }\n newTimestamp =\n _daysFromDate(year, month, day) *\n SECONDS_PER_DAY +\n (timestamp % SECONDS_PER_DAY);\n require(newTimestamp <= timestamp);\n }\n\n function subDays(uint timestamp, uint _days)\n internal\n pure\n returns (uint newTimestamp)\n {\n newTimestamp = timestamp - _days * SECONDS_PER_DAY;\n require(newTimestamp <= timestamp);\n }\n\n function subHours(uint timestamp, uint _hours)\n internal\n pure\n returns (uint newTimestamp)\n {\n newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;\n require(newTimestamp <= timestamp);\n }\n\n function subMinutes(uint timestamp, uint _minutes)\n internal\n pure\n returns (uint newTimestamp)\n {\n newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;\n require(newTimestamp <= timestamp);\n }\n\n function subSeconds(uint timestamp, uint _seconds)\n internal\n pure\n returns (uint newTimestamp)\n {\n newTimestamp = timestamp - _seconds;\n require(newTimestamp <= timestamp);\n }\n\n function diffYears(uint fromTimestamp, uint toTimestamp)\n internal\n pure\n returns (uint _years)\n {\n require(fromTimestamp <= toTimestamp);\n (uint fromYear, , ) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);\n (uint toYear, , ) = _daysToDate(toTimestamp / SECONDS_PER_DAY);\n _years = toYear - fromYear;\n }\n\n function diffMonths(uint fromTimestamp, uint toTimestamp)\n internal\n pure\n returns (uint _months)\n {\n require(fromTimestamp <= toTimestamp);\n (uint fromYear, uint fromMonth, ) = _daysToDate(\n fromTimestamp / SECONDS_PER_DAY\n );\n (uint toYear, uint toMonth, ) = _daysToDate(\n toTimestamp / SECONDS_PER_DAY\n );\n _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;\n }\n\n function diffDays(uint fromTimestamp, uint toTimestamp)\n internal\n pure\n returns (uint _days)\n {\n require(fromTimestamp <= toTimestamp);\n _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;\n }\n\n function diffHours(uint fromTimestamp, uint toTimestamp)\n internal\n pure\n returns (uint _hours)\n {\n require(fromTimestamp <= toTimestamp);\n _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;\n }\n\n function diffMinutes(uint fromTimestamp, uint toTimestamp)\n internal\n pure\n returns (uint _minutes)\n {\n require(fromTimestamp <= toTimestamp);\n _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;\n }\n\n function diffSeconds(uint fromTimestamp, uint toTimestamp)\n internal\n pure\n returns (uint _seconds)\n {\n require(fromTimestamp <= toTimestamp);\n _seconds = toTimestamp - fromTimestamp;\n }\n}\n" + }, + "contracts/libraries/NumbersLib.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n// Libraries\nimport { SafeCast } from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\nimport { Math } from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport \"./WadRayMath.sol\";\n\n/**\n * @dev Utility library for uint256 numbers\n *\n * @author develop@teller.finance\n */\nlibrary NumbersLib {\n using WadRayMath for uint256;\n\n /**\n * @dev It represents 100% with 2 decimal places.\n */\n uint16 internal constant PCT_100 = 10000;\n\n function percentFactor(uint256 decimals) internal pure returns (uint256) {\n return 100 * (10**decimals);\n }\n\n /**\n * @notice Returns a percentage value of a number.\n * @param self The number to get a percentage of.\n * @param percentage The percentage value to calculate with 2 decimal places (10000 = 100%).\n */\n function percent(uint256 self, uint16 percentage)\n internal\n pure\n returns (uint256)\n {\n return percent(self, percentage, 2);\n }\n\n /**\n * @notice Returns a percentage value of a number.\n * @param self The number to get a percentage of.\n * @param percentage The percentage value to calculate with.\n * @param decimals The number of decimals the percentage value is in.\n */\n function percent(uint256 self, uint256 percentage, uint256 decimals)\n internal\n pure\n returns (uint256)\n {\n return (self * percentage) / percentFactor(decimals);\n }\n\n /**\n * @notice it returns the absolute number of a specified parameter\n * @param self the number to be returned in it's absolute\n * @return the absolute number\n */\n function abs(int256 self) internal pure returns (uint256) {\n return self >= 0 ? uint256(self) : uint256(-1 * self);\n }\n\n /**\n * @notice Returns a ratio percentage of {num1} to {num2}.\n * @dev Returned value is type uint16.\n * @param num1 The number used to get the ratio for.\n * @param num2 The number used to get the ratio from.\n * @return Ratio percentage with 2 decimal places (10000 = 100%).\n */\n function ratioOf(uint256 num1, uint256 num2)\n internal\n pure\n returns (uint16)\n {\n return SafeCast.toUint16(ratioOf(num1, num2, 2));\n }\n\n /**\n * @notice Returns a ratio percentage of {num1} to {num2}.\n * @param num1 The number used to get the ratio for.\n * @param num2 The number used to get the ratio from.\n * @param decimals The number of decimals the percentage value is returned in.\n * @return Ratio percentage value.\n */\n function ratioOf(uint256 num1, uint256 num2, uint256 decimals)\n internal\n pure\n returns (uint256)\n {\n if (num2 == 0) return 0;\n return (num1 * percentFactor(decimals)) / num2;\n }\n\n /**\n * @notice Calculates the payment amount for a cycle duration.\n * The formula is calculated based on the standard Estimated Monthly Installment (https://en.wikipedia.org/wiki/Equated_monthly_installment)\n * EMI = [P x R x (1+R)^N]/[(1+R)^N-1]\n * @param principal The starting amount that is owed on the loan.\n * @param loanDuration The length of the loan.\n * @param cycleDuration The length of the loan's payment cycle.\n * @param apr The annual percentage rate of the loan.\n */\n function pmt(\n uint256 principal,\n uint32 loanDuration,\n uint32 cycleDuration,\n uint16 apr,\n uint256 daysInYear\n ) internal pure returns (uint256) {\n require(\n loanDuration >= cycleDuration,\n \"PMT: cycle duration < loan duration\"\n );\n if (apr == 0)\n return\n Math.mulDiv(\n principal,\n cycleDuration,\n loanDuration,\n Math.Rounding.Up\n );\n\n // Number of payment cycles for the duration of the loan\n uint256 n = Math.ceilDiv(loanDuration, cycleDuration);\n\n uint256 one = WadRayMath.wad();\n uint256 r = WadRayMath.pctToWad(apr).wadMul(cycleDuration).wadDiv(\n daysInYear\n );\n uint256 exp = (one + r).wadPow(n);\n uint256 numerator = principal.wadMul(r).wadMul(exp);\n uint256 denominator = exp - one;\n\n return numerator.wadDiv(denominator);\n }\n}\n" + }, + "contracts/libraries/uniswap/core/interfaces/callback/IUniswapV3FlashCallback.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#flash\n/// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface\ninterface IUniswapV3FlashCallback {\n /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash.\n /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// @param fee0 The fee amount in token0 due to the pool by the end of the flash\n /// @param fee1 The fee amount in token1 due to the pool by the end of the flash\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n}\n" + }, + "contracts/libraries/uniswap/core/interfaces/callback/IUniswapV3SwapCallback.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n /// @dev In the implementation you must pay the pool tokens owed for the swap.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external;\n}\n" + }, + "contracts/libraries/uniswap/core/interfaces/IUniswapV3Factory.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title The interface for the Uniswap V3 Factory\n/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees\ninterface IUniswapV3Factory {\n /// @notice Emitted when the owner of the factory is changed\n /// @param oldOwner The owner before the owner was changed\n /// @param newOwner The owner after the owner was changed\n event OwnerChanged(address indexed oldOwner, address indexed newOwner);\n\n /// @notice Emitted when a pool is created\n /// @param token0 The first token of the pool by address sort order\n /// @param token1 The second token of the pool by address sort order\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks\n /// @param pool The address of the created pool\n event PoolCreated(\n address indexed token0,\n address indexed token1,\n uint24 indexed fee,\n int24 tickSpacing,\n address pool\n );\n\n /// @notice Emitted when a new fee amount is enabled for pool creation via the factory\n /// @param fee The enabled fee, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee\n event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);\n\n /// @notice Returns the current owner of the factory\n /// @dev Can be changed by the current owner via setOwner\n /// @return The address of the factory owner\n function owner() external view returns (address);\n\n /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled\n /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context\n /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee\n /// @return The tick spacing\n function feeAmountTickSpacing(uint24 fee) external view returns (int24);\n\n /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist\n /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order\n /// @param tokenA The contract address of either token0 or token1\n /// @param tokenB The contract address of the other token\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @return pool The pool address\n function getPool(\n address tokenA,\n address tokenB,\n uint24 fee\n ) external view returns (address pool);\n\n /// @notice Creates a pool for the given two tokens and fee\n /// @param tokenA One of the two tokens in the desired pool\n /// @param tokenB The other of the two tokens in the desired pool\n /// @param fee The desired fee for the pool\n /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved\n /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments\n /// are invalid.\n /// @return pool The address of the newly created pool\n function createPool(\n address tokenA,\n address tokenB,\n uint24 fee\n ) external returns (address pool);\n\n /// @notice Updates the owner of the factory\n /// @dev Must be called by the current owner\n /// @param _owner The new owner of the factory\n function setOwner(address _owner) external;\n\n /// @notice Enables a fee amount with the given tickSpacing\n /// @dev Fee amounts may never be removed once enabled\n /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)\n /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount\n function enableFeeAmount(uint24 fee, int24 tickSpacing) external;\n}\n" + }, + "contracts/libraries/uniswap/core/interfaces/IUniswapV3Pool.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport './pool/IUniswapV3PoolImmutables.sol';\nimport './pool/IUniswapV3PoolState.sol';\nimport './pool/IUniswapV3PoolDerivedState.sol';\nimport './pool/IUniswapV3PoolActions.sol';\nimport './pool/IUniswapV3PoolOwnerActions.sol';\nimport './pool/IUniswapV3PoolEvents.sol';\n\n/// @title The interface for a Uniswap V3 Pool\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\n/// to the ERC20 specification\n/// @dev The pool interface is broken up into many smaller pieces\ninterface IUniswapV3Pool is\n IUniswapV3PoolImmutables,\n IUniswapV3PoolState,\n IUniswapV3PoolDerivedState,\n IUniswapV3PoolActions,\n IUniswapV3PoolOwnerActions,\n IUniswapV3PoolEvents\n{\n\n}\n" + }, + "contracts/libraries/uniswap/core/interfaces/pool/IUniswapV3PoolActions.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @notice Contains pool methods that can be called by anyone\ninterface IUniswapV3PoolActions {\n /// @notice Sets the initial price for the pool\n /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\n function initialize(uint160 sqrtPriceX96) external;\n\n /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\n /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\n /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n /// on tickLower, tickUpper, the amount of liquidity, and the current price.\n /// @param recipient The address for which the liquidity will be created\n /// @param tickLower The lower tick of the position in which to add liquidity\n /// @param tickUpper The upper tick of the position in which to add liquidity\n /// @param amount The amount of liquidity to mint\n /// @param data Any data that should be passed through to the callback\n /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n function mint(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount,\n bytes calldata data\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Collects tokens owed to a position\n /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n /// @param recipient The address which should receive the fees collected\n /// @param tickLower The lower tick of the position for which to collect fees\n /// @param tickUpper The upper tick of the position for which to collect fees\n /// @param amount0Requested How much token0 should be withdrawn from the fees owed\n /// @param amount1Requested How much token1 should be withdrawn from the fees owed\n /// @return amount0 The amount of fees collected in token0\n /// @return amount1 The amount of fees collected in token1\n function collect(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n\n /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n /// @dev Fees must be collected separately via a call to #collect\n /// @param tickLower The lower tick of the position for which to burn liquidity\n /// @param tickUpper The upper tick of the position for which to burn liquidity\n /// @param amount How much liquidity to burn\n /// @return amount0 The amount of token0 sent to the recipient\n /// @return amount1 The amount of token1 sent to the recipient\n function burn(\n int24 tickLower,\n int24 tickUpper,\n uint128 amount\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Swap token0 for token1, or token1 for token0\n /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\n /// @param recipient The address to receive the output of the swap\n /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\n /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\n /// @param data Any data to be passed through to the callback\n /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n function swap(\n address recipient,\n bool zeroForOne,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bytes calldata data\n ) external returns (int256 amount0, int256 amount1);\n\n /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\n /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\n /// with 0 amount{0,1} and sending the donation amount(s) from the callback\n /// @param recipient The address which will receive the token0 and token1 amounts\n /// @param amount0 The amount of token0 to send\n /// @param amount1 The amount of token1 to send\n /// @param data Any data to be passed through to the callback\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external;\n\n /// @notice Increase the maximum number of price and liquidity observations that this pool will store\n /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\n /// the input observationCardinalityNext.\n /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\n function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n}\n" + }, + "contracts/libraries/uniswap/core/interfaces/pool/IUniswapV3PoolDerivedState.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that is not stored\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\n/// blockchain. The functions here may have variable gas costs.\ninterface IUniswapV3PoolDerivedState {\n /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n /// you must call it with secondsAgos = [3600, 0].\n /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\n /// timestamp\n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\n\n /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\n /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\n /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\n /// snapshot is taken and the second snapshot is taken.\n /// @param tickLower The lower tick of the range\n /// @param tickUpper The upper tick of the range\n /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\n /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\n /// @return secondsInside The snapshot of seconds per liquidity for the range\n function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n external\n view\n returns (\n int56 tickCumulativeInside,\n uint160 secondsPerLiquidityInsideX128,\n uint32 secondsInside\n );\n}\n" + }, + "contracts/libraries/uniswap/core/interfaces/pool/IUniswapV3PoolEvents.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Events emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolEvents {\n /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\n /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\n /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\n /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\n event Initialize(uint160 sqrtPriceX96, int24 tick);\n\n /// @notice Emitted when liquidity is minted for a given position\n /// @param sender The address that minted the liquidity\n /// @param owner The owner of the position and recipient of any minted liquidity\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity minted to the position range\n /// @param amount0 How much token0 was required for the minted liquidity\n /// @param amount1 How much token1 was required for the minted liquidity\n event Mint(\n address sender,\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted when fees are collected by the owner of a position\n /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\n /// @param owner The owner of the position for which fees are collected\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount0 The amount of token0 fees collected\n /// @param amount1 The amount of token1 fees collected\n event Collect(\n address indexed owner,\n address recipient,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount0,\n uint128 amount1\n );\n\n /// @notice Emitted when a position's liquidity is removed\n /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\n /// @param owner The owner of the position for which liquidity is removed\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity to remove\n /// @param amount0 The amount of token0 withdrawn\n /// @param amount1 The amount of token1 withdrawn\n event Burn(\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted by the pool for any swaps between token0 and token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the output of the swap\n /// @param amount0 The delta of the token0 balance of the pool\n /// @param amount1 The delta of the token1 balance of the pool\n /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n /// @param liquidity The liquidity of the pool after the swap\n /// @param tick The log base 1.0001 of price of the pool after the swap\n event Swap(\n address indexed sender,\n address indexed recipient,\n int256 amount0,\n int256 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick\n );\n\n /// @notice Emitted by the pool for any flashes of token0/token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the tokens from flash\n /// @param amount0 The amount of token0 that was flashed\n /// @param amount1 The amount of token1 that was flashed\n /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\n /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\n event Flash(\n address indexed sender,\n address indexed recipient,\n uint256 amount0,\n uint256 amount1,\n uint256 paid0,\n uint256 paid1\n );\n\n /// @notice Emitted by the pool for increases to the number of observations that can be stored\n /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\n /// just before a mint/swap/burn.\n /// @param observationCardinalityNextOld The previous value of the next observation cardinality\n /// @param observationCardinalityNextNew The updated value of the next observation cardinality\n event IncreaseObservationCardinalityNext(\n uint16 observationCardinalityNextOld,\n uint16 observationCardinalityNextNew\n );\n\n /// @notice Emitted when the protocol fee is changed by the pool\n /// @param feeProtocol0Old The previous value of the token0 protocol fee\n /// @param feeProtocol1Old The previous value of the token1 protocol fee\n /// @param feeProtocol0New The updated value of the token0 protocol fee\n /// @param feeProtocol1New The updated value of the token1 protocol fee\n event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);\n\n /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\n /// @param sender The address that collects the protocol fees\n /// @param recipient The address that receives the collected protocol fees\n /// @param amount0 The amount of token0 protocol fees that is withdrawn\n /// @param amount0 The amount of token1 protocol fees that is withdrawn\n event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);\n}\n" + }, + "contracts/libraries/uniswap/core/interfaces/pool/IUniswapV3PoolImmutables.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that never changes\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\ninterface IUniswapV3PoolImmutables {\n /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\n /// @return The contract address\n function factory() external view returns (address);\n\n /// @notice The first of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token0() external view returns (address);\n\n /// @notice The second of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token1() external view returns (address);\n\n /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\n /// @return The fee\n function fee() external view returns (uint24);\n\n /// @notice The pool tick spacing\n /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\n /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\n /// This value is an int24 to avoid casting even though it is always positive.\n /// @return The tick spacing\n function tickSpacing() external view returns (int24);\n\n /// @notice The maximum amount of position liquidity that can use any tick in the range\n /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\n /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\n /// @return The max amount of liquidity per tick\n function maxLiquidityPerTick() external view returns (uint128);\n}\n" + }, + "contracts/libraries/uniswap/core/interfaces/pool/IUniswapV3PoolOwnerActions.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissioned pool actions\n/// @notice Contains pool methods that may only be called by the factory owner\ninterface IUniswapV3PoolOwnerActions {\n /// @notice Set the denominator of the protocol's % share of the fees\n /// @param feeProtocol0 new protocol fee for token0 of the pool\n /// @param feeProtocol1 new protocol fee for token1 of the pool\n function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\n\n /// @notice Collect the protocol fee accrued to the pool\n /// @param recipient The address to which collected protocol fees should be sent\n /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\n /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\n /// @return amount0 The protocol fee collected in token0\n /// @return amount1 The protocol fee collected in token1\n function collectProtocol(\n address recipient,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n}\n" + }, + "contracts/libraries/uniswap/core/interfaces/pool/IUniswapV3PoolState.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\n/// per transaction\ninterface IUniswapV3PoolState {\n /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\n /// when accessed externally.\n /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\n /// tick The current tick of the pool, i.e. according to the last tick transition that was run.\n /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\n /// boundary.\n /// observationIndex The index of the last oracle observation that was written,\n /// observationCardinality The current maximum number of observations stored in the pool,\n /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n /// feeProtocol The protocol fee for both tokens of the pool.\n /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\n /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\n /// unlocked Whether the pool is currently locked to reentrancy\n function slot0()\n external\n view\n returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint16 observationIndex,\n uint16 observationCardinality,\n uint16 observationCardinalityNext,\n uint8 feeProtocol,\n bool unlocked\n );\n\n /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal0X128() external view returns (uint256);\n\n /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal1X128() external view returns (uint256);\n\n /// @notice The amounts of token0 and token1 that are owed to the protocol\n /// @dev Protocol fees will never exceed uint128 max in either token\n function protocolFees() external view returns (uint128 token0, uint128 token1);\n\n /// @notice The currently in range liquidity available to the pool\n /// @dev This value has no relationship to the total liquidity across all ticks\n function liquidity() external view returns (uint128);\n\n /// @notice Look up information about a specific tick in the pool\n /// @param tick The tick to look up\n /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\n /// tick upper,\n /// liquidityNet how much liquidity changes when the pool price crosses the tick,\n /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n /// secondsOutside the seconds spent on the other side of the tick from the current tick,\n /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\n /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\n /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\n /// a specific position.\n function ticks(int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128,\n int56 tickCumulativeOutside,\n uint160 secondsPerLiquidityOutsideX128,\n uint32 secondsOutside,\n bool initialized\n );\n\n /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\n function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n /// @notice Returns the information about a position by the position's key\n /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\n /// @return _liquidity The amount of liquidity in the position,\n /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\n function positions(bytes32 key)\n external\n view\n returns (\n uint128 _liquidity,\n uint256 feeGrowthInside0LastX128,\n uint256 feeGrowthInside1LastX128,\n uint128 tokensOwed0,\n uint128 tokensOwed1\n );\n\n /// @notice Returns data about a specific observation index\n /// @param index The element of the observations array to fetch\n /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\n /// ago, rather than at a specific index in the array.\n /// @return blockTimestamp The timestamp of the observation,\n /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n /// Returns initialized whether the observation has been initialized and the values are safe to use\n function observations(uint256 index)\n external\n view\n returns (\n uint32 blockTimestamp,\n int56 tickCumulative,\n uint160 secondsPerLiquidityCumulativeX128,\n bool initialized\n );\n}\n" + }, + "contracts/libraries/uniswap/core/libraries/LowGasSafeMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.0;\n\n/// @title Optimized overflow and underflow safe math operations\n/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost\nlibrary LowGasSafeMath {\n /// @notice Returns x + y, reverts if sum overflows uint256\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x + y) >= x);\n }\n\n /// @notice Returns x - y, reverts if underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x - y) <= x);\n }\n\n /// @notice Returns x * y, reverts if overflows\n /// @param x The multiplicand\n /// @param y The multiplier\n /// @return z The product of x and y\n function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require(x == 0 || (z = x * y) / x == y);\n }\n\n /// @notice Returns x + y, reverts if overflows or underflows\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(int256 x, int256 y) internal pure returns (int256 z) {\n require((z = x + y) >= x == (y >= 0));\n }\n\n /// @notice Returns x - y, reverts if overflows or underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(int256 x, int256 y) internal pure returns (int256 z) {\n require((z = x - y) <= x == (y >= 0));\n }\n}\n" + }, + "contracts/libraries/uniswap/FixedPoint96.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.4.0;\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\n/// @dev Used in SqrtPriceMath.sol\nlibrary FixedPoint96 {\n uint8 internal constant RESOLUTION = 96;\n uint256 internal constant Q96 = 0x1000000000000000000000000;\n}\n" + }, + "contracts/libraries/uniswap/FullMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n function mulDiv(uint256 a, uint256 b, uint256 denominator)\n internal\n pure\n returns (uint256 result)\n {\n // 512-bit multiply [prod1 prod0] = a * b\n // Compute the product mod 2**256 and mod 2**256 - 1\n // then use the Chinese Remainder Theorem to reconstruct\n // 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(a, b, not(0))\n prod0 := mul(a, b)\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 require(denominator > 0);\n assembly {\n result := div(prod0, denominator)\n }\n return result;\n }\n\n // Make sure the result is less than 2**256.\n // 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 // Compute remainder using mulmod\n uint256 remainder;\n assembly {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly {\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator\n // Compute largest power of two divisor of denominator.\n // Always >= 1.\n // uint256 twos = -denominator & denominator;\n uint256 twos = (~denominator + 1) & denominator;\n // Divide denominator by power of two\n assembly {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly {\n prod0 := div(prod0, twos)\n }\n // Shift in bits from prod1 into prod0. For this we need\n // to flip `twos` such that it is 2**256 / twos.\n // If twos is zero, then it becomes one\n assembly {\n twos := add(div(sub(0, twos), twos), 1)\n }\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2**256\n // Now that denominator is an odd number, it has an inverse\n // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n // Compute the inverse by starting with a seed that is correct\n // correct for four bits. That is, denominator * inv = 1 mod 2**4\n uint256 inv = (3 * denominator) ^ 2;\n // Now use Newton-Raphson iteration to improve the precision.\n // Thanks to Hensel's lifting lemma, this also works in modular\n // arithmetic, doubling the correct bits in each step.\n inv *= 2 - denominator * inv; // inverse mod 2**8\n inv *= 2 - denominator * inv; // inverse mod 2**16\n inv *= 2 - denominator * inv; // inverse mod 2**32\n inv *= 2 - denominator * inv; // inverse mod 2**64\n inv *= 2 - denominator * inv; // inverse mod 2**128\n inv *= 2 - denominator * inv; // inverse mod 2**256\n\n // Because the division is now exact we can divide by multiplying\n // with the modular inverse of denominator. This will give us the\n // correct result modulo 2**256. Since the precoditions guarantee\n // that the outcome is less than 2**256, this is the final result.\n // We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inv;\n return result;\n }\n\n /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator)\n internal\n pure\n returns (uint256 result)\n {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) > 0) {\n require(result < type(uint256).max);\n result++;\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/base/PeripheryImmutableState.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\nimport '../interfaces/IPeripheryImmutableState.sol';\n\n/// @title Immutable state\n/// @notice Immutable state used by periphery contracts\nabstract contract PeripheryImmutableState is IPeripheryImmutableState {\n /// @inheritdoc IPeripheryImmutableState\n address public immutable override factory;\n /// @inheritdoc IPeripheryImmutableState\n address public immutable override WETH9;\n\n constructor(address _factory, address _WETH9) {\n factory = _factory;\n WETH9 = _WETH9;\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/base/PeripheryPayments.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\nimport '../interfaces/IPeripheryPayments.sol';\nimport '../interfaces/external/IWETH9.sol';\n\nimport '../libraries/TransferHelper.sol';\n\nimport './PeripheryImmutableState.sol';\n\nabstract contract PeripheryPayments is IPeripheryPayments, PeripheryImmutableState {\n receive() external payable {\n require(msg.sender == WETH9, 'Not WETH9');\n }\n\n /// @inheritdoc IPeripheryPayments\n function unwrapWETH9(uint256 amountMinimum, address recipient) public payable override {\n uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));\n require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9');\n\n if (balanceWETH9 > 0) {\n IWETH9(WETH9).withdraw(balanceWETH9);\n TransferHelper.safeTransferETH(recipient, balanceWETH9);\n }\n }\n\n /// @inheritdoc IPeripheryPayments\n function sweepToken(\n address token,\n uint256 amountMinimum,\n address recipient\n ) public payable override {\n uint256 balanceToken = IERC20(token).balanceOf(address(this));\n require(balanceToken >= amountMinimum, 'Insufficient token');\n\n if (balanceToken > 0) {\n TransferHelper.safeTransfer(token, recipient, balanceToken);\n }\n }\n\n /// @inheritdoc IPeripheryPayments\n function refundETH() external payable override {\n if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance);\n }\n\n /// @param token The token to pay\n /// @param payer The entity that must pay\n /// @param recipient The entity that will receive payment\n /// @param value The amount to pay\n function pay(\n address token,\n address payer,\n address recipient,\n uint256 value\n ) internal {\n if (token == WETH9 && address(this).balance >= value) {\n // pay with WETH9\n IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay\n IWETH9(WETH9).transfer(recipient, value);\n } else if (payer == address(this)) {\n // pay with tokens already in the contract (for the exact input multihop case)\n TransferHelper.safeTransfer(token, recipient, value);\n } else {\n // pull payment\n TransferHelper.safeTransferFrom(token, payer, recipient, value);\n }\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/external/IWETH9.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\n/// @title Interface for WETH9\ninterface IWETH9 is IERC20 {\n /// @notice Deposit ether to get wrapped ether\n function deposit() external payable;\n\n /// @notice Withdraw wrapped ether to get ether\n function withdraw(uint256) external;\n}\n" + }, + "contracts/libraries/uniswap/periphery/interfaces/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/libraries/uniswap/periphery/interfaces/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) external 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/libraries/uniswap/periphery/interfaces/ISwapRouter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport '../../core/interfaces/callback/IUniswapV3SwapCallback.sol';\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via Uniswap V3\ninterface ISwapRouter is IUniswapV3SwapCallback {\n struct ExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactInputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\n\n struct ExactOutputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/CallbackValidation.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n\nimport '../../core/interfaces/IUniswapV3Pool.sol';\nimport './PoolAddress.sol';\n\n/// @notice Provides validation for callbacks from Uniswap V3 Pools\nlibrary CallbackValidation {\n /// @notice Returns the address of a valid Uniswap V3 Pool\n /// @param factory The contract address of the Uniswap V3 factory\n /// @param tokenA The contract address of either token0 or token1\n /// @param tokenB The contract address of the other token\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @return pool The V3 pool contract address\n function verifyCallback(\n address factory,\n address tokenA,\n address tokenB,\n uint24 fee\n ) internal view returns (IUniswapV3Pool pool) {\n return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));\n }\n\n /// @notice Returns the address of a valid Uniswap V3 Pool\n /// @param factory The contract address of the Uniswap V3 factory\n /// @param poolKey The identifying key of the V3 pool\n /// @return pool The V3 pool contract address\n function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey)\n internal\n view\n returns (IUniswapV3Pool pool)\n {\n pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));\n require(msg.sender == address(pool));\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/PoolAddress.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.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 = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;\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) internal pure returns (address pool) {\n require(key.token0 < key.token1);\n pool = address(\n uint160(uint256(\n keccak256(\n abi.encodePacked(\n hex'ff',\n factory,\n keccak256(abi.encode(key.token0, key.token1, key.fee)),\n POOL_INIT_CODE_HASH\n )\n )\n ) )\n );\n }\n}\n" + }, + "contracts/libraries/uniswap/periphery/libraries/TransferHelper.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.6.0;\n\nimport '@openzeppelin/contracts/token/ERC20/IERC20.sol';\n\nlibrary TransferHelper {\n /// @notice Transfers tokens from the targeted address to the given destination\n /// @notice Errors with 'STF' if transfer fails\n /// @param token The contract address of the token to be transferred\n /// @param from The originating address from which the tokens will be transferred\n /// @param to The destination address of the transfer\n /// @param value The amount to be transferred\n function safeTransferFrom(\n address token,\n address from,\n address to,\n uint256 value\n ) internal {\n (bool success, bytes memory data) =\n token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');\n }\n\n /// @notice Transfers tokens from msg.sender to a recipient\n /// @dev Errors with ST if transfer fails\n /// @param token The contract address of the token which will be transferred\n /// @param to The recipient of the transfer\n /// @param value The value of the transfer\n function safeTransfer(\n address token,\n address to,\n uint256 value\n ) internal {\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');\n }\n\n /// @notice Approves the stipulated contract to spend the given allowance in the given token\n /// @dev Errors with 'SA' if transfer fails\n /// @param token The contract address of the token to be approved\n /// @param to The target of the approval\n /// @param value The amount of the given token the target will be allowed to spend\n function safeApprove(\n address token,\n address to,\n uint256 value\n ) internal {\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));\n require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');\n }\n\n /// @notice Transfers ETH to the recipient address\n /// @dev Fails with `STE`\n /// @param to The destination of the transfer\n /// @param value The value to be transferred\n function safeTransferETH(address to, uint256 value) internal {\n (bool success, ) = to.call{value: value}(new bytes(0));\n require(success, 'STE');\n }\n}\n" + }, + "contracts/libraries/uniswap/TickMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.0;\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\n/// prices between 2**-128 and 2**128\nlibrary TickMath {\n /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128\n int24 internal constant MIN_TICK = -887272;\n /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128\n int24 internal constant MAX_TICK = -MIN_TICK;\n\n /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\n uint160 internal constant MIN_SQRT_RATIO = 4295128739;\n /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\n uint160 internal constant MAX_SQRT_RATIO =\n 1461446703485210103287273052203988822378723970342;\n\n /// @notice Calculates sqrt(1.0001^tick) * 2^96\n /// @dev Throws if |tick| > max tick\n /// @param tick The input tick for the above formula\n /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\n /// at the given tick\n function getSqrtRatioAtTick(int24 tick)\n internal\n pure\n returns (uint160 sqrtPriceX96)\n {\n uint256 absTick = tick < 0\n ? uint256(-int256(tick))\n : uint256(int256(tick));\n require(absTick <= uint256(uint24(MAX_TICK)), \"T\");\n\n uint256 ratio = absTick & 0x1 != 0\n ? 0xfffcb933bd6fad37aa2d162d1a594001\n : 0x100000000000000000000000000000000;\n if (absTick & 0x2 != 0)\n ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\n if (absTick & 0x4 != 0)\n ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n if (absTick & 0x8 != 0)\n ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n if (absTick & 0x10 != 0)\n ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n if (absTick & 0x20 != 0)\n ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n if (absTick & 0x40 != 0)\n ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n if (absTick & 0x80 != 0)\n ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n if (absTick & 0x100 != 0)\n ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n if (absTick & 0x200 != 0)\n ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n if (absTick & 0x400 != 0)\n ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n if (absTick & 0x800 != 0)\n ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n if (absTick & 0x1000 != 0)\n ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n if (absTick & 0x2000 != 0)\n ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n if (absTick & 0x4000 != 0)\n ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n if (absTick & 0x8000 != 0)\n ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n if (absTick & 0x10000 != 0)\n ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n if (absTick & 0x20000 != 0)\n ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\n if (absTick & 0x40000 != 0)\n ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n if (absTick & 0x80000 != 0)\n ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\n\n if (tick > 0) ratio = type(uint256).max / ratio;\n\n // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\n sqrtPriceX96 = uint160(\n (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)\n );\n }\n\n /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\n /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\n /// ever return.\n /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\n /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\n function getTickAtSqrtRatio(uint160 sqrtPriceX96)\n internal\n pure\n returns (int24 tick)\n {\n // second inequality must be < because the price can never reach the price at the max tick\n require(\n sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO,\n \"R\"\n );\n uint256 ratio = uint256(sqrtPriceX96) << 32;\n\n uint256 r = ratio;\n uint256 msb = 0;\n\n assembly {\n let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(5, gt(r, 0xFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(4, gt(r, 0xFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(3, gt(r, 0xFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(2, gt(r, 0xF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(1, gt(r, 0x3))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := gt(r, 0x1)\n msb := or(msb, f)\n }\n\n if (msb >= 128) r = ratio >> (msb - 127);\n else r = ratio << (127 - msb);\n\n int256 log_2 = (int256(msb) - 128) << 64;\n\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(63, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(62, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(61, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(60, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(59, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(58, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(57, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(56, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(55, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(54, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(53, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(52, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(51, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(50, f))\n }\n\n int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\n\n int24 tickLow = int24(\n (log_sqrt10001 - 3402992956809132418596140100660247210) >> 128\n );\n int24 tickHi = int24(\n (log_sqrt10001 + 291339464771989622907027621153398088495) >> 128\n );\n\n tick = tickLow == tickHi\n ? tickLow\n : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96\n ? tickHi\n : tickLow;\n }\n}\n" + }, + "contracts/libraries/UniswapPricingLibraryV2.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n \n\nimport {IUniswapPricingLibrary} from \"../interfaces/IUniswapPricingLibrary.sol\";\n\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\n\n \nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\n\n// Libraries\nimport { MathUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol\";\n\nimport \"../interfaces/uniswap/IUniswapV3Pool.sol\"; \n\nimport \"../libraries/uniswap/TickMath.sol\";\nimport \"../libraries/uniswap/FixedPoint96.sol\";\nimport \"../libraries/uniswap/FullMath.sol\";\n \n \nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n\n/*\n\nOnly do decimal expansion if it is an ERC20 not anything else !! \n\n*/\n\nlibrary UniswapPricingLibraryV2\n{\n \n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\n\n \n function getUniswapPriceRatioForPoolRoutes(\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolRoutes\n ) public view returns (uint256 priceRatio) {\n require(poolRoutes.length <= 2, \"invalid pool routes length\");\n\n if (poolRoutes.length == 2) {\n uint256 pool0PriceRatio = getUniswapPriceRatioForPool(\n poolRoutes[0]\n );\n\n uint256 pool1PriceRatio = getUniswapPriceRatioForPool(\n poolRoutes[1]\n );\n\n return\n FullMath.mulDiv(\n pool0PriceRatio,\n pool1PriceRatio,\n STANDARD_EXPANSION_FACTOR\n );\n } else if (poolRoutes.length == 1) {\n return getUniswapPriceRatioForPool(poolRoutes[0]);\n }\n\n //else return 0\n }\n\n /*\n The resultant product is expanded by STANDARD_EXPANSION_FACTOR one time \n */\n function getUniswapPriceRatioForPool(\n IUniswapPricingLibrary.PoolRouteConfig memory _poolRouteConfig\n ) public view returns (uint256 priceRatio) {\n\n \n\n // this is expanded by 2**96 or 1e28 \n uint160 sqrtPriceX96 = getSqrtTwapX96(\n _poolRouteConfig.pool,\n _poolRouteConfig.twapInterval\n );\n\n\n bool invert = ! _poolRouteConfig.zeroForOne; \n\n //this output will be expanded by 1e18 \n return getQuoteFromSqrtRatioX96( sqrtPriceX96 , uint128( STANDARD_EXPANSION_FACTOR ), invert) ;\n\n\n \n }\n\n\n //taken directly from uniswap oracle lib \n /**\n * @dev Calculates the amount of quote token received for a given amount of base token\n * based on the square root of the price ratio (sqrtRatioX96).\n *\n * @param sqrtRatioX96 The square root of the price ratio(in terms of token1/token0) between two tokens, encoded as a Q64.96 value.\n * @param baseAmount The amount of the base token for which the quote is to be calculated. Specify 1e18 for a price(quoteAmount) with 18 decimals of precision.\n * @param inverse Specifies the direction of the price quote. If true then baseAmount must be the amount of token1, if false then baseAmount must be the amount for token0\n *\n * @return quoteAmount The calculated amount of the quote token for the specified baseAmount\n */\n\n function getQuoteFromSqrtRatioX96(\n uint160 sqrtRatioX96,\n uint128 baseAmount,\n bool inverse\n ) internal pure returns (uint256 quoteAmount) {\n // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself\n if (sqrtRatioX96 <= type(uint128).max) {\n uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;\n quoteAmount = !inverse\n ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\n : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\n } else {\n uint256 ratioX128 = FullMath.mulDiv(\n sqrtRatioX96,\n sqrtRatioX96,\n 1 << 64\n );\n quoteAmount = !inverse\n ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\n : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\n }\n }\n \n\n function getSqrtTwapX96(address uniswapV3Pool, uint32 twapInterval)\n internal\n view\n returns (uint160 sqrtPriceX96)\n {\n if (twapInterval == 0) {\n // return the current price if twapInterval == 0\n (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0();\n } else {\n uint32[] memory secondsAgos = new uint32[](2);\n secondsAgos[0] = twapInterval + 1; // from (before)\n secondsAgos[1] = 1; // one block prior\n\n (int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapV3Pool)\n .observe(secondsAgos);\n\n // tick(imprecise as it's an integer) to price\n sqrtPriceX96 = TickMath.getSqrtRatioAtTick(\n int24(\n (tickCumulatives[1] - tickCumulatives[0]) /\n int32(twapInterval)\n )\n );\n }\n }\n\n function getPriceX96FromSqrtPriceX96(uint160 sqrtPriceX96)\n internal\n pure\n returns (uint256 priceX96)\n { \n\n \n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96);\n }\n\n}" + }, + "contracts/libraries/V2Calculations.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n\n// SPDX-License-Identifier: MIT\n\n// Libraries\nimport \"./NumbersLib.sol\";\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport { Bid } from \"../TellerV2Storage.sol\";\nimport { BokkyPooBahsDateTimeLibrary as BPBDTL } from \"./DateTimeLib.sol\";\n\nenum PaymentType {\n EMI,\n Bullet\n}\n\nenum PaymentCycleType {\n Seconds,\n Monthly\n}\n\nlibrary V2Calculations {\n using NumbersLib for uint256;\n\n /**\n * @notice Returns the timestamp of the last payment made for a loan.\n * @param _bid The loan bid struct to get the timestamp for.\n */\n function lastRepaidTimestamp(Bid storage _bid)\n internal\n view\n returns (uint32)\n {\n return\n _bid.loanDetails.lastRepaidTimestamp == 0\n ? _bid.loanDetails.acceptedTimestamp\n : _bid.loanDetails.lastRepaidTimestamp;\n }\n\n /**\n * @notice Calculates the amount owed for a loan.\n * @param _bid The loan bid struct to get the owed amount for.\n * @param _timestamp The timestamp at which to get the owed amount at.\n * @param _paymentCycleType The payment cycle type of the loan (Seconds or Monthly).\n */\n function calculateAmountOwed(\n Bid storage _bid,\n uint256 _timestamp,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentCycleDuration\n )\n public\n view\n returns (\n uint256 owedPrincipal_,\n uint256 duePrincipal_,\n uint256 interest_\n )\n {\n // Total principal left to pay\n return\n calculateAmountOwed(\n _bid,\n lastRepaidTimestamp(_bid),\n _timestamp,\n _paymentCycleType,\n _paymentCycleDuration\n );\n }\n\n function calculateAmountOwed(\n Bid storage _bid,\n uint256 _lastRepaidTimestamp,\n uint256 _timestamp,\n PaymentCycleType _paymentCycleType,\n uint32 _paymentCycleDuration\n )\n public\n view\n returns (\n uint256 owedPrincipal_,\n uint256 duePrincipal_,\n uint256 interest_\n )\n {\n owedPrincipal_ =\n _bid.loanDetails.principal -\n _bid.loanDetails.totalRepaid.principal;\n\n uint256 owedTime = _timestamp - uint256(_lastRepaidTimestamp);\n\n {\n uint256 daysInYear = _paymentCycleType == PaymentCycleType.Monthly\n ? 360 days\n : 365 days;\n\n uint256 interestOwedInAYear = owedPrincipal_.percent(_bid.terms.APR, 2);\n \n interest_ = (interestOwedInAYear * owedTime) / daysInYear;\n }\n\n\n bool isLastPaymentCycle;\n {\n uint256 lastPaymentCycleDuration = _bid.loanDetails.loanDuration %\n _paymentCycleDuration;\n if (lastPaymentCycleDuration == 0) {\n lastPaymentCycleDuration = _paymentCycleDuration;\n }\n\n uint256 endDate = uint256(_bid.loanDetails.acceptedTimestamp) +\n uint256(_bid.loanDetails.loanDuration);\n uint256 lastPaymentCycleStart = endDate -\n uint256(lastPaymentCycleDuration);\n\n isLastPaymentCycle =\n uint256(_timestamp) > lastPaymentCycleStart ||\n owedPrincipal_ + interest_ <= _bid.terms.paymentCycleAmount;\n }\n\n if (_bid.paymentType == PaymentType.Bullet) {\n if (isLastPaymentCycle) {\n duePrincipal_ = owedPrincipal_;\n }\n } else {\n // Default to PaymentType.EMI\n // Max payable amount in a cycle\n // NOTE: the last cycle could have less than the calculated payment amount\n\n //the amount owed for the cycle should never exceed the current payment cycle amount so we use min here \n uint256 owedAmountForCycle = Math.min( ((_bid.terms.paymentCycleAmount * owedTime) ) /\n _paymentCycleDuration , _bid.terms.paymentCycleAmount+interest_ ) ;\n\n uint256 owedAmount = isLastPaymentCycle\n ? owedPrincipal_ + interest_\n : owedAmountForCycle ;\n\n duePrincipal_ = Math.min(owedAmount - interest_, owedPrincipal_);\n }\n }\n\n /**\n * @notice Calculates the amount owed for a loan for the next payment cycle.\n * @param _type The payment type of the loan.\n * @param _cycleType The cycle type set for the loan. (Seconds or Monthly)\n * @param _principal The starting amount that is owed on the loan.\n * @param _duration The length of the loan.\n * @param _paymentCycle The length of the loan's payment cycle.\n * @param _apr The annual percentage rate of the loan.\n */\n function calculatePaymentCycleAmount(\n PaymentType _type,\n PaymentCycleType _cycleType,\n uint256 _principal,\n uint32 _duration,\n uint32 _paymentCycle,\n uint16 _apr\n ) public view returns (uint256) {\n uint256 daysInYear = _cycleType == PaymentCycleType.Monthly\n ? 360 days\n : 365 days;\n if (_type == PaymentType.Bullet) {\n return\n _principal.percent(_apr).percent(\n uint256(_paymentCycle).ratioOf(daysInYear, 10),\n 10\n );\n }\n // Default to PaymentType.EMI\n return\n NumbersLib.pmt(\n _principal,\n _duration,\n _paymentCycle,\n _apr,\n daysInYear\n );\n }\n\n function calculateNextDueDate(\n uint32 _acceptedTimestamp,\n uint32 _paymentCycle,\n uint32 _loanDuration,\n uint32 _lastRepaidTimestamp,\n PaymentCycleType _bidPaymentCycleType\n ) public view returns (uint32 dueDate_) {\n // Calculate due date if payment cycle is set to monthly\n if (_bidPaymentCycleType == PaymentCycleType.Monthly) {\n // Calculate the cycle number the last repayment was made\n uint256 lastPaymentCycle = BPBDTL.diffMonths(\n _acceptedTimestamp,\n _lastRepaidTimestamp\n );\n if (\n BPBDTL.getDay(_lastRepaidTimestamp) >\n BPBDTL.getDay(_acceptedTimestamp)\n ) {\n lastPaymentCycle += 2;\n } else {\n lastPaymentCycle += 1;\n }\n\n dueDate_ = uint32(\n BPBDTL.addMonths(_acceptedTimestamp, lastPaymentCycle)\n );\n } else if (_bidPaymentCycleType == PaymentCycleType.Seconds) {\n // Start with the original due date being 1 payment cycle since bid was accepted\n dueDate_ = _acceptedTimestamp + _paymentCycle;\n // Calculate the cycle number the last repayment was made\n uint32 delta = _lastRepaidTimestamp - _acceptedTimestamp;\n if (delta > 0) {\n uint32 repaymentCycle = uint32(\n Math.ceilDiv(delta, _paymentCycle)\n );\n dueDate_ += (repaymentCycle * _paymentCycle);\n }\n }\n\n uint32 endOfLoan = _acceptedTimestamp + _loanDuration;\n //if we are in the last payment cycle, the next due date is the end of loan duration\n if (dueDate_ > endOfLoan) {\n dueDate_ = endOfLoan;\n }\n }\n}\n" + }, + "contracts/libraries/WadRayMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\nimport \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\n\n/**\n * @title WadRayMath library\n * @author Multiplier Finance\n * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)\n */\nlibrary WadRayMath {\n using SafeMath for uint256;\n\n uint256 internal constant WAD = 1e18;\n uint256 internal constant halfWAD = WAD / 2;\n\n uint256 internal constant RAY = 1e27;\n uint256 internal constant halfRAY = RAY / 2;\n\n uint256 internal constant WAD_RAY_RATIO = 1e9;\n uint256 internal constant PCT_WAD_RATIO = 1e14;\n uint256 internal constant PCT_RAY_RATIO = 1e23;\n\n function ray() internal pure returns (uint256) {\n return RAY;\n }\n\n function wad() internal pure returns (uint256) {\n return WAD;\n }\n\n function halfRay() internal pure returns (uint256) {\n return halfRAY;\n }\n\n function halfWad() internal pure returns (uint256) {\n return halfWAD;\n }\n\n function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {\n return halfWAD.add(a.mul(b)).div(WAD);\n }\n\n function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 halfB = b / 2;\n\n return halfB.add(a.mul(WAD)).div(b);\n }\n\n function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {\n return halfRAY.add(a.mul(b)).div(RAY);\n }\n\n function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 halfB = b / 2;\n\n return halfB.add(a.mul(RAY)).div(b);\n }\n\n function rayToWad(uint256 a) internal pure returns (uint256) {\n uint256 halfRatio = WAD_RAY_RATIO / 2;\n\n return halfRatio.add(a).div(WAD_RAY_RATIO);\n }\n\n function rayToPct(uint256 a) internal pure returns (uint16) {\n uint256 halfRatio = PCT_RAY_RATIO / 2;\n\n uint256 val = halfRatio.add(a).div(PCT_RAY_RATIO);\n return SafeCast.toUint16(val);\n }\n\n function wadToPct(uint256 a) internal pure returns (uint16) {\n uint256 halfRatio = PCT_WAD_RATIO / 2;\n\n uint256 val = halfRatio.add(a).div(PCT_WAD_RATIO);\n return SafeCast.toUint16(val);\n }\n\n function wadToRay(uint256 a) internal pure returns (uint256) {\n return a.mul(WAD_RAY_RATIO);\n }\n\n function pctToRay(uint16 a) internal pure returns (uint256) {\n return uint256(a).mul(RAY).div(1e4);\n }\n\n function pctToWad(uint16 a) internal pure returns (uint256) {\n return uint256(a).mul(WAD).div(1e4);\n }\n\n /**\n * @dev calculates base^duration. The code uses the ModExp precompile\n * @return z base^duration, in ray\n */\n function rayPow(uint256 x, uint256 n) internal pure returns (uint256) {\n return _pow(x, n, RAY, rayMul);\n }\n\n function wadPow(uint256 x, uint256 n) internal pure returns (uint256) {\n return _pow(x, n, WAD, wadMul);\n }\n\n function _pow(\n uint256 x,\n uint256 n,\n uint256 p,\n function(uint256, uint256) internal pure returns (uint256) mul\n ) internal pure returns (uint256 z) {\n z = n % 2 != 0 ? x : p;\n\n for (n /= 2; n != 0; n /= 2) {\n x = mul(x, x);\n\n if (n % 2 != 0) {\n z = mul(z, x);\n }\n }\n }\n}\n" + }, + "contracts/mock/LenderCommitmentGroup_SmartMock.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n//import \"../TellerV2MarketForwarder.sol\";\n\nimport \"../TellerV2Context.sol\";\n\n//import { LenderCommitmentForwarder } from \"../contracts/LenderCommitmentForwarder.sol\";\n\nimport \"../interfaces/ITellerV2.sol\";\nimport \"../interfaces/ILenderCommitmentForwarder.sol\";\nimport \"../interfaces/ILenderCommitmentGroup.sol\";\nimport \"../interfaces/ISmartCommitment.sol\";\n\nimport \"../interfaces/ITellerV2MarketForwarder.sol\";\n\nimport { Collateral, CollateralType } from \"../interfaces/escrow/ICollateralEscrowV1.sol\";\n\nimport \"../mock/MarketRegistryMock.sol\";\n\ncontract LenderCommitmentGroup_SmartMock is\n ILenderCommitmentGroup,\n ISmartCommitment\n{\n\n\n constructor(\n address _tellerV2,\n address _smartCommitmentForwarder,\n address _uniswapV3Factory\n ) {\n //TELLER_V2 = _tellerV2;\n //SMART_COMMITMENT_FORWARDER = _smartCommitmentForwarder;\n //UNISWAP_V3_FACTORY = _uniswapV3Factory;\n }\n\n\n\n function initialize(\n CommitmentGroupConfig calldata _commitmentGroupConfig,\n IUniswapPricingLibrary.PoolRouteConfig[] calldata _poolOracleRoutes \n )\n external\n returns (\n //uint256 _maxPrincipalPerCollateralAmount //use oracle instead\n\n //ILenderCommitmentForwarder.Commitment calldata _createCommitmentArgs\n\n address poolSharesToken\n ){\n\n\n }\n\n function addPrincipalToCommitmentGroup(\n uint256 _amount,\n address _sharesRecipient,\n uint256 _minAmountOut\n ) external returns (uint256 sharesAmount_){\n\n \n }\n\n\n\n function prepareSharesForBurn(\n uint256 _amountPoolSharesTokens \n ) external returns (bool){\n\n \n }\n\n function burnSharesToWithdrawEarnings(\n uint256 _amountPoolSharesTokens,\n address _recipient,\n uint256 _minAmountOut\n ) external returns (uint256){\n\n \n }\n\n\n function liquidateDefaultedLoanWithIncentive(\n uint256 _bidId,\n int256 _tokenAmountDifference\n ) external{\n\n \n }\n\n function getTokenDifferenceFromLiquidations() external view returns (int256){\n\n \n }\n\n\n\n\n\n function getPrincipalTokenAddress() external view returns (address){\n\n \n }\n\n function getMarketId() external view returns (uint256){\n\n \n }\n\n function getCollateralTokenAddress() external view returns (address){\n\n \n }\n\n function getCollateralTokenType()\n external\n view\n returns (CommitmentCollateralType){\n\n \n }\n\n function getCollateralTokenId() external view returns (uint256){\n\n \n }\n\n function getMinInterestRate(uint256 _delta) external view returns (uint16){\n\n \n }\n\n function getMaxLoanDuration() external view returns (uint32){\n\n \n }\n\n function getPrincipalAmountAvailableToBorrow()\n external\n view\n returns (uint256){\n\n \n }\n\n function getRequiredCollateral(\n uint256 _principalAmount,\n uint256 _maxPrincipalPerCollateralAmount\n \n )\n external\n view\n returns (uint256){\n\n \n }\n\n \n function acceptFundsForAcceptBid(\n address _borrower,\n uint256 _bidId,\n uint256 _principalAmount,\n uint256 _collateralAmount,\n address _collateralTokenAddress,\n uint256 _collateralTokenId,\n uint32 _loanDuration,\n uint16 _interestRate\n ) external{\n\n \n }\n}\n" + }, + "contracts/mock/MarketRegistryMock.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: MIT\n\nimport \"../interfaces/IMarketRegistry.sol\";\nimport { PaymentType } from \"../libraries/V2Calculations.sol\";\n\ncontract MarketRegistryMock is IMarketRegistry {\n //address marketOwner;\n\n address public globalMarketOwner;\n address public globalMarketFeeRecipient;\n bool public globalMarketsClosed;\n\n bool public globalBorrowerIsVerified = true;\n bool public globalLenderIsVerified = true;\n\n constructor() {}\n\n function initialize(TellerAS _tellerAS) external {}\n\n function isVerifiedLender(uint256 _marketId, address _lenderAddress)\n public\n view\n returns (bool isVerified_, bytes32 uuid_)\n {\n isVerified_ = globalLenderIsVerified;\n }\n\n function isMarketOpen(uint256 _marketId) public view returns (bool) {\n return !globalMarketsClosed;\n }\n\n function isMarketClosed(uint256 _marketId) public view returns (bool) {\n return globalMarketsClosed;\n }\n\n function isVerifiedBorrower(uint256 _marketId, address _borrower)\n public\n view\n returns (bool isVerified_, bytes32 uuid_)\n {\n isVerified_ = globalBorrowerIsVerified;\n }\n\n function getMarketOwner(uint256 _marketId)\n public\n view\n override\n returns (address)\n {\n return address(globalMarketOwner);\n }\n\n function getMarketFeeRecipient(uint256 _marketId)\n public\n view\n returns (address)\n {\n return address(globalMarketFeeRecipient);\n }\n\n function getMarketURI(uint256 _marketId)\n public\n view\n returns (string memory)\n {\n return \"url://\";\n }\n\n function getPaymentCycle(uint256 _marketId)\n public\n view\n returns (uint32, PaymentCycleType)\n {\n return (1000, PaymentCycleType.Seconds);\n }\n\n function getPaymentDefaultDuration(uint256 _marketId)\n public\n view\n returns (uint32)\n {\n return 1000;\n }\n\n function getBidExpirationTime(uint256 _marketId)\n public\n view\n returns (uint32)\n {\n return 1000;\n }\n\n function getMarketplaceFee(uint256 _marketId) public view returns (uint16) {\n return 1000;\n }\n\n function setMarketOwner(address _owner) public {\n globalMarketOwner = _owner;\n }\n\n function setMarketFeeRecipient(address _feeRecipient) public {\n globalMarketFeeRecipient = _feeRecipient;\n }\n\n function getPaymentType(uint256 _marketId)\n public\n view\n returns (PaymentType)\n {}\n\n function createMarket(\n address _initialOwner,\n uint32 _paymentCycleDuration,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _requireLenderAttestation,\n bool _requireBorrowerAttestation,\n PaymentType _paymentType,\n PaymentCycleType _paymentCycleType,\n string calldata _uri\n ) public returns (uint256) {}\n\n function createMarket(\n address _initialOwner,\n uint32 _paymentCycleDuration,\n uint32 _paymentDefaultDuration,\n uint32 _bidExpirationTime,\n uint16 _feePercent,\n bool _requireLenderAttestation,\n bool _requireBorrowerAttestation,\n string calldata _uri\n ) public returns (uint256) {}\n\n function closeMarket(uint256 _marketId) public {}\n\n function mock_setGlobalMarketsClosed(bool closed) public {\n globalMarketsClosed = closed;\n }\n\n function mock_setBorrowerIsVerified(bool verified) public {\n globalBorrowerIsVerified = verified;\n }\n\n function mock_setLenderIsVerified(bool verified) public {\n globalLenderIsVerified = verified;\n }\n}\n" + }, + "contracts/oracleprotection/OracleProtectedChild.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IOracleProtectionManager} from \"../interfaces/oracleprotection/IOracleProtectionManager.sol\";\n\nabstract contract OracleProtectedChild {\n address public immutable ORACLE_MANAGER;\n \n\n modifier onlyOracleApproved() {\n \n IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER);\n require( oracleManager .isOracleApproved(msg.sender ) , \"Oracle: Not Approved\");\n _;\n }\n\n modifier onlyOracleApprovedAllowEOA() {\n \n IOracleProtectionManager oracleManager = IOracleProtectionManager(ORACLE_MANAGER);\n require( oracleManager .isOracleApprovedAllowEOA(msg.sender ) , \"Oracle: Not Approved\");\n _;\n }\n \n constructor(address oracleManager){\n\t\t ORACLE_MANAGER = oracleManager;\n }\n \n}" + }, + "contracts/oracleprotection/OracleProtectionManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n\nimport {IHypernativeOracle} from \"../interfaces/oracleprotection/IHypernativeOracle.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n \n\nimport {IOracleProtectionManager} from \"../interfaces/oracleprotection/IOracleProtectionManager.sol\";\n \n\nabstract contract OracleProtectionManager is \nIOracleProtectionManager, OwnableUpgradeable\n{\n bytes32 private constant HYPERNATIVE_ORACLE_STORAGE_SLOT = bytes32(uint256(keccak256(\"eip1967.hypernative.oracle\")) - 1);\n bytes32 private constant HYPERNATIVE_MODE_STORAGE_SLOT = bytes32(uint256(keccak256(\"eip1967.hypernative.is_strict_mode\")) - 1);\n \n event OracleAddressChanged(address indexed previousOracle, address indexed newOracle);\n \n\n modifier onlyOracleApproved() {\n \n require( isOracleApproved(msg.sender ) , \"Oracle: Not Approved\");\n _;\n }\n\n modifier onlyOracleApprovedAllowEOA() {\n \n require( isOracleApprovedAllowEOA(msg.sender ) , \"Oracle: Not Approved\");\n _;\n }\n \n\n function oracleRegister(address _account) public virtual {\n address oracleAddress = _hypernativeOracle();\n IHypernativeOracle oracle = IHypernativeOracle(oracleAddress);\n if (hypernativeOracleIsStrictMode()) {\n oracle.registerStrict(_account);\n }\n else {\n oracle.register(_account);\n }\n } \n\n\n function isOracleApproved(address _sender) public returns (bool) {\n address oracleAddress = _hypernativeOracle();\n if (oracleAddress == address(0)) { \n return true;\n }\n IHypernativeOracle oracle = IHypernativeOracle(oracleAddress);\n if (oracle.isBlacklistedContext( tx.origin,_sender) || !oracle.isTimeExceeded(_sender)) {\n return false;\n }\n return true;\n }\n\n // Only allow EOA to interact \n function isOracleApprovedOnlyAllowEOA(address _sender) public returns (bool){\n address oracleAddress = _hypernativeOracle();\n if (oracleAddress == address(0)) {\n \n return true;\n }\n\n IHypernativeOracle oracle = IHypernativeOracle(oracleAddress);\n if (oracle.isBlacklistedAccount(_sender) || _sender != tx.origin) {\n return false;\n } \n return true ;\n }\n\n // Always allow EOAs to interact, non-EOA have to register\n function isOracleApprovedAllowEOA(address _sender) public returns (bool){\n address oracleAddress = _hypernativeOracle();\n\n //without an oracle address set, allow all through \n if (oracleAddress == address(0)) {\n return true;\n }\n\n // any accounts are blocked if blacklisted\n IHypernativeOracle oracle = IHypernativeOracle(oracleAddress);\n if (oracle.isBlacklistedContext( tx.origin,_sender) ){\n return false;\n }\n \n //smart contracts (delegate calls) are blocked if they havent registered and waited\n if ( _sender != tx.origin && !oracle.isTimeExceeded(_sender)) {\n return false;\n }\n\n return true ;\n }\n \n \n /*\n * @dev This must be implemented by the parent contract or else the modifiers will always pass through all traffic\n\n */\n function _setOracle(address _oracle) internal {\n address oldOracle = _hypernativeOracle();\n _setAddressBySlot(HYPERNATIVE_ORACLE_STORAGE_SLOT, _oracle);\n emit OracleAddressChanged(oldOracle, _oracle);\n }\n \n\n function _setIsStrictMode(bool _mode) internal {\n _setValueBySlot(HYPERNATIVE_MODE_STORAGE_SLOT, _mode ? 1 : 0);\n }\n\n \n\n function _setAddressBySlot(bytes32 slot, address newAddress) internal {\n assembly {\n sstore(slot, newAddress)\n }\n }\n\n function _setValueBySlot(bytes32 _slot, uint256 _value) internal {\n assembly {\n sstore(_slot, _value)\n }\n }\n\n \n function hypernativeOracleIsStrictMode() public view returns (bool) {\n return _getValueBySlot(HYPERNATIVE_MODE_STORAGE_SLOT) == 1;\n }\n\n function _getAddressBySlot(bytes32 slot) internal view returns (address addr) {\n assembly {\n addr := sload(slot)\n }\n }\n\n function _getValueBySlot(bytes32 _slot) internal view returns (uint256 _value) {\n assembly {\n _value := sload(_slot)\n }\n }\n\n function _hypernativeOracle() internal view returns (address) {\n return _getAddressBySlot(HYPERNATIVE_ORACLE_STORAGE_SLOT);\n }\n\n\n}" + }, + "contracts/ProtocolFee.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\ncontract ProtocolFee is OwnableUpgradeable {\n // Protocol fee set for loan processing.\n uint16 private _protocolFee;\n\n \n /**\n * @notice This event is emitted when the protocol fee has been updated.\n * @param newFee The new protocol fee set.\n * @param oldFee The previously set protocol fee.\n */\n event ProtocolFeeSet(uint16 newFee, uint16 oldFee);\n\n /**\n * @notice Initialized the protocol fee.\n * @param initFee The initial protocol fee to be set on the protocol.\n */\n function __ProtocolFee_init(uint16 initFee) internal onlyInitializing {\n __Ownable_init();\n __ProtocolFee_init_unchained(initFee);\n }\n\n function __ProtocolFee_init_unchained(uint16 initFee)\n internal\n onlyInitializing\n {\n setProtocolFee(initFee);\n }\n\n /**\n * @notice Returns the current protocol fee.\n */\n function protocolFee() public view virtual returns (uint16) {\n return _protocolFee;\n }\n\n /**\n * @notice Lets the DAO/owner of the protocol to set a new protocol fee.\n * @param newFee The new protocol fee to be set.\n */\n function setProtocolFee(uint16 newFee) public virtual onlyOwner {\n // Skip if the fee is the same\n if (newFee == _protocolFee) return;\n\n uint16 oldFee = _protocolFee;\n _protocolFee = newFee;\n emit ProtocolFeeSet(newFee, oldFee);\n }\n}\n" + }, + "contracts/ProtocolFeeMock.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./ProtocolFee.sol\";\n\ncontract ProtocolFeeMock is ProtocolFee {\n bool public setProtocolFeeCalled;\n\n function initialize(uint16 _initFee) external initializer {\n __ProtocolFee_init(_initFee);\n }\n\n function setProtocolFee(uint16 newFee) public override onlyOwner {\n setProtocolFeeCalled = true;\n\n bool _isInitializing;\n assembly {\n _isInitializing := sload(1)\n }\n\n // Only call the actual function if we are not initializing\n if (!_isInitializing) {\n super.setProtocolFee(newFee);\n }\n }\n}\n" + }, + "contracts/TellerV2Context.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./TellerV2Storage.sol\";\nimport \"./ERC2771ContextUpgradeable.sol\";\n\n/**\n * @dev This contract should not use any storage\n */\n\nabstract contract TellerV2Context is\n ERC2771ContextUpgradeable,\n TellerV2Storage\n{\n using EnumerableSet for EnumerableSet.AddressSet;\n\n event TrustedMarketForwarderSet(\n uint256 indexed marketId,\n address forwarder,\n address sender\n );\n event MarketForwarderApproved(\n uint256 indexed marketId,\n address indexed forwarder,\n address sender\n );\n event MarketForwarderRenounced(\n uint256 indexed marketId,\n address indexed forwarder,\n address sender\n );\n\n constructor(address trustedForwarder)\n ERC2771ContextUpgradeable(trustedForwarder)\n {}\n\n /**\n * @notice Checks if an address is a trusted forwarder contract for a given market.\n * @param _marketId An ID for a lending market.\n * @param _trustedMarketForwarder An address to check if is a trusted forwarder in the given market.\n * @return A boolean indicating the forwarder address is trusted in a market.\n */\n function isTrustedMarketForwarder(\n uint256 _marketId,\n address _trustedMarketForwarder\n ) public view returns (bool) {\n return\n _trustedMarketForwarders[_marketId] == _trustedMarketForwarder ||\n lenderCommitmentForwarder == _trustedMarketForwarder;\n }\n\n /**\n * @notice Checks if an account has approved a forwarder for a market.\n * @param _marketId An ID for a lending market.\n * @param _forwarder A forwarder contract address.\n * @param _account The address to verify set an approval.\n * @return A boolean indicating if an approval was set.\n */\n function hasApprovedMarketForwarder(\n uint256 _marketId,\n address _forwarder,\n address _account\n ) public view returns (bool) {\n return\n isTrustedMarketForwarder(_marketId, _forwarder) &&\n _approvedForwarderSenders[_forwarder].contains(_account);\n }\n\n /**\n * @notice Sets a trusted forwarder for a lending market.\n * @notice The caller must owner the market given. See {MarketRegistry}\n * @param _marketId An ID for a lending market.\n * @param _forwarder A forwarder contract address.\n */\n function setTrustedMarketForwarder(uint256 _marketId, address _forwarder)\n external\n {\n require(\n marketRegistry.getMarketOwner(_marketId) == _msgSender(),\n \"Caller must be the market owner\"\n );\n _trustedMarketForwarders[_marketId] = _forwarder;\n emit TrustedMarketForwarderSet(_marketId, _forwarder, _msgSender());\n }\n\n /**\n * @notice Approves a forwarder contract to use their address as a sender for a specific market.\n * @notice The forwarder given must be trusted by the market given.\n * @param _marketId An ID for a lending market.\n * @param _forwarder A forwarder contract address.\n */\n function approveMarketForwarder(uint256 _marketId, address _forwarder)\n external\n {\n require(\n isTrustedMarketForwarder(_marketId, _forwarder),\n \"Forwarder must be trusted by the market\"\n );\n _approvedForwarderSenders[_forwarder].add(_msgSender());\n emit MarketForwarderApproved(_marketId, _forwarder, _msgSender());\n }\n\n /**\n * @notice Renounces approval of a market forwarder\n * @param _marketId An ID for a lending market.\n * @param _forwarder A forwarder contract address.\n */\n function renounceMarketForwarder(uint256 _marketId, address _forwarder)\n external\n {\n if (_approvedForwarderSenders[_forwarder].contains(_msgSender())) {\n _approvedForwarderSenders[_forwarder].remove(_msgSender());\n emit MarketForwarderRenounced(_marketId, _forwarder, _msgSender());\n }\n }\n\n /**\n * @notice Retrieves the function caller address by checking the appended calldata if the _actual_ caller is a trusted forwarder.\n * @param _marketId An ID for a lending market.\n * @return sender The address to use as the function caller.\n */\n function _msgSenderForMarket(uint256 _marketId)\n internal\n view\n virtual\n returns (address)\n {\n if (\n msg.data.length >= 20 &&\n isTrustedMarketForwarder(_marketId, _msgSender())\n ) {\n address sender;\n assembly {\n sender := shr(96, calldataload(sub(calldatasize(), 20)))\n }\n // Ensure the appended sender address approved the forwarder\n require(\n _approvedForwarderSenders[_msgSender()].contains(sender),\n \"Sender must approve market forwarder\"\n );\n return sender;\n }\n\n return _msgSender();\n }\n\n /**\n * @notice Retrieves the actual function calldata from a trusted forwarder call.\n * @param _marketId An ID for a lending market to verify if the caller is a trusted forwarder.\n * @return calldata The modified bytes array of the function calldata without the appended sender's address.\n */\n function _msgDataForMarket(uint256 _marketId)\n internal\n view\n virtual\n returns (bytes calldata)\n {\n if (isTrustedMarketForwarder(_marketId, _msgSender())) {\n return msg.data[:msg.data.length - 20];\n } else {\n return _msgData();\n }\n }\n}\n" + }, + "contracts/TellerV2MarketForwarder_G1.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./interfaces/ITellerV2.sol\";\n\nimport \"./interfaces/IMarketRegistry.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\n/**\n * @dev Simple helper contract to forward an encoded function call to the TellerV2 contract. See {TellerV2Context}\n */\nabstract contract TellerV2MarketForwarder_G1 is\n Initializable,\n ContextUpgradeable\n{\n using AddressUpgradeable for address;\n\n address public immutable _tellerV2;\n address public immutable _marketRegistry;\n\n struct CreateLoanArgs {\n uint256 marketId;\n address lendingToken;\n uint256 principal;\n uint32 duration;\n uint16 interestRate;\n string metadataURI;\n address recipient;\n }\n\n constructor(address _protocolAddress, address _marketRegistryAddress) {\n _tellerV2 = _protocolAddress;\n _marketRegistry = _marketRegistryAddress;\n }\n\n function getTellerV2() public view returns (address) {\n return _tellerV2;\n }\n\n function getMarketRegistry() public view returns (address) {\n return _marketRegistry;\n }\n\n function getTellerV2MarketOwner(uint256 marketId) public returns (address) {\n return IMarketRegistry(getMarketRegistry()).getMarketOwner(marketId);\n }\n\n /**\n * @dev Performs function call to the TellerV2 contract by appending an address to the calldata.\n * @param _data The encoded function calldata on TellerV2.\n * @param _msgSender The address that should be treated as the underlying function caller.\n * @return The encoded response from the called function.\n *\n * Requirements:\n * - The {_msgSender} address must set an approval on TellerV2 for this forwarder contract __before__ making this call.\n */\n function _forwardCall(bytes memory _data, address _msgSender)\n internal\n returns (bytes memory)\n {\n return\n address(_tellerV2).functionCall(\n abi.encodePacked(_data, _msgSender)\n );\n }\n\n /**\n * @notice Creates a new loan using the TellerV2 lending protocol.\n * @param _createLoanArgs Details describing the loan agreement.]\n * @param _borrower The borrower address for the new loan.\n */\n function _submitBid(\n CreateLoanArgs memory _createLoanArgs,\n address _borrower\n ) internal virtual returns (uint256 bidId) {\n bytes memory responseData;\n\n responseData = _forwardCall(\n abi.encodeWithSignature(\n \"submitBid(address,uint256,uint256,uint32,uint16,string,address)\",\n _createLoanArgs.lendingToken,\n _createLoanArgs.marketId,\n _createLoanArgs.principal,\n _createLoanArgs.duration,\n _createLoanArgs.interestRate,\n _createLoanArgs.metadataURI,\n _createLoanArgs.recipient\n ),\n _borrower\n );\n\n return abi.decode(responseData, (uint256));\n }\n\n /**\n * @notice Creates a new loan using the TellerV2 lending protocol.\n * @param _createLoanArgs Details describing the loan agreement.]\n * @param _borrower The borrower address for the new loan.\n */\n function _submitBidWithCollateral(\n CreateLoanArgs memory _createLoanArgs,\n Collateral[] memory _collateralInfo,\n address _borrower\n ) internal virtual returns (uint256 bidId) {\n bytes memory responseData;\n\n responseData = _forwardCall(\n abi.encodeWithSignature(\n \"submitBid(address,uint256,uint256,uint32,uint16,string,address,(uint8,uint256,uint256,address)[])\",\n _createLoanArgs.lendingToken,\n _createLoanArgs.marketId,\n _createLoanArgs.principal,\n _createLoanArgs.duration,\n _createLoanArgs.interestRate,\n _createLoanArgs.metadataURI,\n _createLoanArgs.recipient,\n _collateralInfo\n ),\n _borrower\n );\n\n return abi.decode(responseData, (uint256));\n }\n\n /**\n * @notice Accepts a new loan using the TellerV2 lending protocol.\n * @param _bidId The id of the new loan.\n * @param _lender The address of the lender who will provide funds for the new loan.\n */\n function _acceptBid(uint256 _bidId, address _lender)\n internal\n virtual\n returns (bool)\n {\n // Approve the borrower's loan\n _forwardCall(\n abi.encodeWithSelector(ITellerV2.lenderAcceptBid.selector, _bidId),\n _lender\n );\n\n return true;\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" + }, + "contracts/TellerV2MarketForwarder_G2.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./interfaces/ITellerV2.sol\";\n\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/ITellerV2MarketForwarder.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\n/**\n * @dev Simple helper contract to forward an encoded function call to the TellerV2 contract. See {TellerV2Context}\n */\nabstract contract TellerV2MarketForwarder_G2 is\n Initializable,\n ContextUpgradeable,\n ITellerV2MarketForwarder\n{\n using AddressUpgradeable for address;\n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable _tellerV2;\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable _marketRegistry;\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _protocolAddress, address _marketRegistryAddress) {\n _tellerV2 = _protocolAddress;\n _marketRegistry = _marketRegistryAddress;\n }\n\n function getTellerV2() public view returns (address) {\n return _tellerV2;\n }\n\n function getMarketRegistry() public view returns (address) {\n return _marketRegistry;\n }\n\n function getTellerV2MarketOwner(uint256 marketId) public returns (address) {\n return IMarketRegistry(getMarketRegistry()).getMarketOwner(marketId);\n }\n\n /**\n * @dev Performs function call to the TellerV2 contract by appending an address to the calldata.\n * @param _data The encoded function calldata on TellerV2.\n * @param _msgSender The address that should be treated as the underlying function caller.\n * @return The encoded response from the called function.\n *\n * Requirements:\n * - The {_msgSender} address must set an approval on TellerV2 for this forwarder contract __before__ making this call.\n */\n function _forwardCall(bytes memory _data, address _msgSender)\n internal\n returns (bytes memory)\n {\n return\n address(_tellerV2).functionCall(\n abi.encodePacked(_data, _msgSender)\n );\n }\n\n /**\n * @notice Creates a new loan using the TellerV2 lending protocol.\n * @param _createLoanArgs Details describing the loan agreement.]\n * @param _borrower The borrower address for the new loan.\n */\n /*function _submitBid(\n CreateLoanArgs memory _createLoanArgs,\n address _borrower\n ) internal virtual returns (uint256 bidId) {\n bytes memory responseData;\n\n responseData = _forwardCall(\n abi.encodeWithSignature(\n \"submitBid(address,uint256,uint256,uint32,uint16,string,address)\",\n _createLoanArgs.lendingToken,\n _createLoanArgs.marketId,\n _createLoanArgs.principal,\n _createLoanArgs.duration,\n _createLoanArgs.interestRate,\n _createLoanArgs.metadataURI,\n _createLoanArgs.recipient\n ),\n _borrower\n );\n\n return abi.decode(responseData, (uint256));\n }*/\n\n /**\n * @notice Creates a new loan using the TellerV2 lending protocol.\n * @param _createLoanArgs Details describing the loan agreement.]\n * @param _borrower The borrower address for the new loan.\n */\n function _submitBidWithCollateral(\n CreateLoanArgs memory _createLoanArgs,\n address _borrower\n ) internal virtual returns (uint256 bidId) {\n bytes memory responseData;\n\n responseData = _forwardCall(\n abi.encodeWithSignature(\n \"submitBid(address,uint256,uint256,uint32,uint16,string,address,(uint8,uint256,uint256,address)[])\",\n _createLoanArgs.lendingToken,\n _createLoanArgs.marketId,\n _createLoanArgs.principal,\n _createLoanArgs.duration,\n _createLoanArgs.interestRate,\n _createLoanArgs.metadataURI,\n _createLoanArgs.recipient,\n _createLoanArgs.collateral\n ),\n _borrower\n );\n\n return abi.decode(responseData, (uint256));\n }\n\n /**\n * @notice Accepts a new loan using the TellerV2 lending protocol.\n * @param _bidId The id of the new loan.\n * @param _lender The address of the lender who will provide funds for the new loan.\n */\n function _acceptBid(uint256 _bidId, address _lender)\n internal\n virtual\n returns (bool)\n {\n // Approve the borrower's loan\n _forwardCall(\n abi.encodeWithSelector(ITellerV2.lenderAcceptBid.selector, _bidId),\n _lender\n );\n\n return true;\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" + }, + "contracts/TellerV2MarketForwarder_G3.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"./interfaces/ITellerV2.sol\";\n\nimport \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/ITellerV2MarketForwarder.sol\";\nimport \"./interfaces/ILoanRepaymentCallbacks.sol\";\n\nimport \"./TellerV2MarketForwarder_G2.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol\";\n\n/**\n * @dev Simple helper contract to forward an encoded function call to the TellerV2 contract. See {TellerV2Context}\n */\nabstract contract TellerV2MarketForwarder_G3 is TellerV2MarketForwarder_G2 {\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _protocolAddress, address _marketRegistryAddress)\n TellerV2MarketForwarder_G2(_protocolAddress, _marketRegistryAddress)\n {}\n\n /**\n * @notice Accepts a new loan using the TellerV2 lending protocol.\n * @param _bidId The id of the new loan.\n * @param _lender The address of the lender who will provide funds for the new loan.\n */\n function _acceptBidWithRepaymentListener(\n uint256 _bidId,\n address _lender,\n address _listener\n ) internal virtual returns (bool) {\n // Approve the borrower's loan\n _forwardCall(\n abi.encodeWithSelector(ITellerV2.lenderAcceptBid.selector, _bidId),\n _lender\n );\n\n _forwardCall(\n abi.encodeWithSelector(\n ILoanRepaymentCallbacks.setRepaymentListenerForBid.selector,\n _bidId,\n _listener\n ),\n _lender\n );\n\n //ITellerV2(getTellerV2()).setRepaymentListenerForBid(_bidId, _listener);\n\n return true;\n }\n\n //a gap is inherited from g2 so this is actually not necessary going forwards ---leaving it to maintain upgradeability\n uint256[50] private __gap;\n}\n" + }, + "contracts/TellerV2Storage.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport { IMarketRegistry } from \"./interfaces/IMarketRegistry.sol\";\nimport \"./interfaces/IEscrowVault.sol\";\nimport \"./interfaces/IReputationManager.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./interfaces/ICollateralManager.sol\";\nimport { PaymentType, PaymentCycleType } from \"./libraries/V2Calculations.sol\";\nimport \"./interfaces/ILenderManager.sol\";\n\nenum BidState {\n NONEXISTENT,\n PENDING,\n CANCELLED,\n ACCEPTED,\n PAID,\n LIQUIDATED,\n CLOSED\n}\n\n/**\n * @notice Represents a total amount for a payment.\n * @param principal Amount that counts towards the principal.\n * @param interest Amount that counts toward interest.\n */\nstruct Payment {\n uint256 principal;\n uint256 interest;\n}\n\n/**\n * @notice Details about a loan request.\n * @param borrower Account address who is requesting a loan.\n * @param receiver Account address who will receive the loan amount.\n * @param lender Account address who accepted and funded the loan request.\n * @param marketplaceId ID of the marketplace the bid was submitted to.\n * @param metadataURI ID of off chain metadata to find additional information of the loan request.\n * @param loanDetails Struct of the specific loan details.\n * @param terms Struct of the loan request terms.\n * @param state Represents the current state of the loan.\n */\nstruct Bid {\n address borrower;\n address receiver;\n address lender; // if this is the LenderManager address, we use that .owner() as source of truth\n uint256 marketplaceId;\n bytes32 _metadataURI; // DEPRECATED\n LoanDetails loanDetails;\n Terms terms;\n BidState state;\n PaymentType paymentType;\n}\n\n/**\n * @notice Details about the loan.\n * @param lendingToken The token address for the loan.\n * @param principal The amount of tokens initially lent out.\n * @param totalRepaid Payment struct that represents the total principal and interest amount repaid.\n * @param timestamp Timestamp, in seconds, of when the bid was submitted by the borrower.\n * @param acceptedTimestamp Timestamp, in seconds, of when the bid was accepted by the lender.\n * @param lastRepaidTimestamp Timestamp, in seconds, of when the last payment was made\n * @param loanDuration The duration of the loan.\n */\nstruct LoanDetails {\n IERC20 lendingToken;\n uint256 principal;\n Payment totalRepaid;\n uint32 timestamp;\n uint32 acceptedTimestamp;\n uint32 lastRepaidTimestamp;\n uint32 loanDuration;\n}\n\n/**\n * @notice Information on the terms of a loan request\n * @param paymentCycleAmount Value of tokens expected to be repaid every payment cycle.\n * @param paymentCycle Duration, in seconds, of how often a payment must be made.\n * @param APR Annual percentage rating to be applied on repayments. (10000 == 100%)\n */\nstruct Terms {\n uint256 paymentCycleAmount;\n uint32 paymentCycle;\n uint16 APR;\n}\n\nabstract contract TellerV2Storage_G0 {\n /** Storage Variables */\n\n // Current number of bids.\n uint256 public bidId;\n\n // Mapping of bidId to bid information.\n mapping(uint256 => Bid) public bids;\n\n // Mapping of borrowers to borrower requests.\n mapping(address => uint256[]) public borrowerBids;\n\n // Mapping of volume filled by lenders.\n mapping(address => uint256) public __lenderVolumeFilled; // DEPRECIATED\n\n // Volume filled by all lenders.\n uint256 public __totalVolumeFilled; // DEPRECIATED\n\n // List of allowed lending tokens\n EnumerableSet.AddressSet internal __lendingTokensSet; // DEPRECATED\n\n IMarketRegistry public marketRegistry;\n IReputationManager public reputationManager;\n\n // Mapping of borrowers to borrower requests.\n mapping(address => EnumerableSet.UintSet) internal _borrowerBidsActive;\n\n mapping(uint256 => uint32) public bidDefaultDuration;\n mapping(uint256 => uint32) public bidExpirationTime;\n\n // Mapping of volume filled by lenders.\n // Asset address => Lender address => Volume amount\n mapping(address => mapping(address => uint256)) public lenderVolumeFilled;\n\n // Volume filled by all lenders.\n // Asset address => Volume amount\n mapping(address => uint256) public totalVolumeFilled;\n\n uint256 public version;\n\n // Mapping of metadataURIs by bidIds.\n // Bid Id => metadataURI string\n mapping(uint256 => string) public uris;\n}\n\nabstract contract TellerV2Storage_G1 is TellerV2Storage_G0 {\n // market ID => trusted forwarder\n mapping(uint256 => address) internal _trustedMarketForwarders;\n // trusted forwarder => set of pre-approved senders\n mapping(address => EnumerableSet.AddressSet)\n internal _approvedForwarderSenders;\n}\n\nabstract contract TellerV2Storage_G2 is TellerV2Storage_G1 {\n address public lenderCommitmentForwarder;\n}\n\nabstract contract TellerV2Storage_G3 is TellerV2Storage_G2 {\n ICollateralManager public collateralManager;\n}\n\nabstract contract TellerV2Storage_G4 is TellerV2Storage_G3 {\n // Address of the lender manager contract\n ILenderManager public lenderManager;\n // BidId to payment cycle type (custom or monthly)\n mapping(uint256 => PaymentCycleType) public bidPaymentCycleType;\n}\n\nabstract contract TellerV2Storage_G5 is TellerV2Storage_G4 {\n // Address of the lender manager contract\n IEscrowVault public escrowVault;\n}\n\nabstract contract TellerV2Storage_G6 is TellerV2Storage_G5 {\n mapping(uint256 => address) public repaymentListenerForBid;\n}\n\nabstract contract TellerV2Storage_G7 is TellerV2Storage_G6 {\n mapping(address => bool) private __pauserRoleBearer;\n bool private __liquidationsPaused; \n}\n\nabstract contract TellerV2Storage_G8 is TellerV2Storage_G7 {\n address protocolFeeRecipient; \n}\n\nabstract contract TellerV2Storage is TellerV2Storage_G8 {}\n" + }, + "contracts/TLR.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol\";\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\ncontract TLR is ERC20Votes, Ownable {\n uint224 private immutable MAX_SUPPLY;\n\n /**\n * @dev Sets the value of the `cap`. This value is immutable, it can only be\n * set once during construction.\n */\n constructor(uint224 _supplyCap, address tokenOwner)\n ERC20(\"Teller\", \"TLR\")\n ERC20Permit(\"Teller\")\n {\n require(_supplyCap > 0, \"ERC20Capped: cap is 0\");\n MAX_SUPPLY = _supplyCap;\n _transferOwnership(tokenOwner);\n }\n\n /**\n * @dev Max supply has been overridden to cap the token supply upon initialization of the contract\n * @dev See OpenZeppelin's implementation of ERC20Votes _mint() function\n */\n function _maxSupply() internal view override returns (uint224) {\n return MAX_SUPPLY;\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function mint(address account, uint256 amount) external onlyOwner {\n _mint(account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function burn(address account, uint256 amount) external onlyOwner {\n _burn(account, amount);\n }\n}\n" + }, + "contracts/Types.sol": { + "content": "pragma solidity >=0.8.0 <0.9.0;\n// SPDX-License-Identifier: MIT\n\n// A representation of an empty/uninitialized UUID.\nbytes32 constant EMPTY_UUID = 0;\n" + } + }, + "settings": { + "optimizer": { + "enabled": true, + "runs": 200 + }, + "outputSelection": { + "*": { + "*": [ + "abi", + "evm.bytecode", + "evm.deployedBytecode", + "evm.methodIdentifiers", + "metadata", + "devdoc", + "userdoc", + "storageLayout", + "evm.gasEstimates" + ], + "": [ + "ast" + ] + } + }, + "metadata": { + "useLiteralContent": true + } + } +} \ No newline at end of file From 89d5c400a8cfab328e3b899a69c0a5653c911e90 Mon Sep 17 00:00:00 2001 From: andy Date: Thu, 3 Apr 2025 15:38:25 -0400 Subject: [PATCH 5/6] deployed LCFA v2 on mainnet --- packages/contracts/.openzeppelin/mainnet.json | 346 +----- .../deployments/mainnet/.migrations.json | 3 +- .../mainnet/LenderCommitmentForwarderV2.json | 1107 +++++++++++++++++ .../mainnet/UniswapPricingLibraryV2.json | 133 ++ 4 files changed, 1244 insertions(+), 345 deletions(-) create mode 100644 packages/contracts/deployments/mainnet/LenderCommitmentForwarderV2.json create mode 100644 packages/contracts/deployments/mainnet/UniswapPricingLibraryV2.json diff --git a/packages/contracts/.openzeppelin/mainnet.json b/packages/contracts/.openzeppelin/mainnet.json index c7388437f..e6aeaff0e 100644 --- a/packages/contracts/.openzeppelin/mainnet.json +++ b/packages/contracts/.openzeppelin/mainnet.json @@ -102,12 +102,7 @@ }, { "address": "0x48EA70BCe76FE2F0c79B29Bf852a1DCF957982aa", - "txHash": "0x7e8f21528b3824eb26e6a6ac0310c2f8c6c1e2add4b9161dc4aec8b4c56f2f09", - "kind": "transparent" - }, - { - "address": "0x208289DD22D4cf59fb18A2CE073A128D5286bD2F", - "txHash": "0x2211b5b2c477b70208d4ff989c35e3125d5aaeda172982f3e2ffc535945ee536", + "txHash": "0xb07c28093b21124a67581081bfe249db62abbce021982702d82e3728320cc61b", "kind": "transparent" } ], @@ -9010,344 +9005,7 @@ }, "9b740c2b4e19814db8909083e4ca64fadf98da46629a44ad77352c135152b8ca": { "address": "0xC764a44Faa62dB04310e0c8eA8d56FDC411e3e31", - "txHash": "0x73b4ceb16b58ea4583b1a111ae458344cba70a78a3404c7618dfc82fa0458ce2", - "layout": { - "solcVersion": "0.8.11", - "storage": [ - { - "label": "userExtensions", - "offset": 0, - "slot": "0", - "type": "t_mapping(t_address,t_mapping(t_address,t_bool))", - "contract": "ExtensionsContextUpgradeable", - "src": "contracts/LenderCommitmentForwarder/extensions/ExtensionsContextUpgradeable.sol:12" - }, - { - "label": "__gap", - "offset": 0, - "slot": "1", - "type": "t_array(t_uint256)49_storage", - "contract": "ExtensionsContextUpgradeable", - "src": "contracts/LenderCommitmentForwarder/extensions/ExtensionsContextUpgradeable.sol:61" - }, - { - "label": "_initialized", - "offset": 0, - "slot": "50", - "type": "t_uint8", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:62", - "retypedFrom": "bool" - }, - { - "label": "_initializing", - "offset": 1, - "slot": "50", - "type": "t_bool", - "contract": "Initializable", - "src": "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol:67" - }, - { - "label": "__gap", - "offset": 0, - "slot": "51", - "type": "t_array(t_uint256)50_storage", - "contract": "ContextUpgradeable", - "src": "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol:36" - }, - { - "label": "__gap", - "offset": 0, - "slot": "101", - "type": "t_array(t_uint256)50_storage", - "contract": "TellerV2MarketForwarder_G2", - "src": "contracts/TellerV2MarketForwarder_G2.sol:149" - }, - { - "label": "commitments", - "offset": 0, - "slot": "151", - "type": "t_mapping(t_uint256,t_struct(Commitment)19680_storage)", - "contract": "LenderCommitmentForwarder_U2", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:58" - }, - { - "label": "commitmentCount", - "offset": 0, - "slot": "152", - "type": "t_uint256", - "contract": "LenderCommitmentForwarder_U2", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:60" - }, - { - "label": "commitmentBorrowersList", - "offset": 0, - "slot": "153", - "type": "t_mapping(t_uint256,t_struct(AddressSet)2837_storage)", - "contract": "LenderCommitmentForwarder_U2", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:63" - }, - { - "label": "commitmentPrincipalAccepted", - "offset": 0, - "slot": "154", - "type": "t_mapping(t_uint256,t_uint256)", - "contract": "LenderCommitmentForwarder_U2", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:67" - }, - { - "label": "commitmentUniswapPoolRoutes", - "offset": 0, - "slot": "155", - "type": "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)20596_storage)dyn_storage)", - "contract": "LenderCommitmentForwarder_U2", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:69" - }, - { - "label": "commitmentPoolOracleLtvRatio", - "offset": 0, - "slot": "156", - "type": "t_mapping(t_uint256,t_uint16)", - "contract": "LenderCommitmentForwarder_U2", - "src": "contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol:71" - } - ], - "types": { - "t_address": { - "label": "address", - "numberOfBytes": "20" - }, - "t_array(t_bytes32)dyn_storage": { - "label": "bytes32[]", - "numberOfBytes": "32" - }, - "t_array(t_struct(PoolRouteConfig)20596_storage)dyn_storage": { - "label": "struct IUniswapPricingLibrary.PoolRouteConfig[]", - "numberOfBytes": "32" - }, - "t_array(t_uint256)49_storage": { - "label": "uint256[49]", - "numberOfBytes": "1568" - }, - "t_array(t_uint256)50_storage": { - "label": "uint256[50]", - "numberOfBytes": "1600" - }, - "t_bool": { - "label": "bool", - "numberOfBytes": "1" - }, - "t_bytes32": { - "label": "bytes32", - "numberOfBytes": "32" - }, - "t_enum(CommitmentCollateralType)19656": { - "label": "enum ILenderCommitmentForwarder_U2.CommitmentCollateralType", - "members": [ - "NONE", - "ERC20", - "ERC721", - "ERC1155", - "ERC721_ANY_ID", - "ERC1155_ANY_ID", - "ERC721_MERKLE_PROOF", - "ERC1155_MERKLE_PROOF" - ], - "numberOfBytes": "1" - }, - "t_mapping(t_address,t_bool)": { - "label": "mapping(address => bool)", - "numberOfBytes": "32" - }, - "t_mapping(t_address,t_mapping(t_address,t_bool))": { - "label": "mapping(address => mapping(address => bool))", - "numberOfBytes": "32" - }, - "t_mapping(t_bytes32,t_uint256)": { - "label": "mapping(bytes32 => uint256)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_array(t_struct(PoolRouteConfig)20596_storage)dyn_storage)": { - "label": "mapping(uint256 => struct IUniswapPricingLibrary.PoolRouteConfig[])", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(AddressSet)2837_storage)": { - "label": "mapping(uint256 => struct EnumerableSetUpgradeable.AddressSet)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_struct(Commitment)19680_storage)": { - "label": "mapping(uint256 => struct ILenderCommitmentForwarder_U2.Commitment)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint16)": { - "label": "mapping(uint256 => uint16)", - "numberOfBytes": "32" - }, - "t_mapping(t_uint256,t_uint256)": { - "label": "mapping(uint256 => uint256)", - "numberOfBytes": "32" - }, - "t_struct(AddressSet)2837_storage": { - "label": "struct EnumerableSetUpgradeable.AddressSet", - "members": [ - { - "label": "_inner", - "type": "t_struct(Set)2522_storage", - "offset": 0, - "slot": "0" - } - ], - "numberOfBytes": "64" - }, - "t_struct(Commitment)19680_storage": { - "label": "struct ILenderCommitmentForwarder_U2.Commitment", - "members": [ - { - "label": "maxPrincipal", - "type": "t_uint256", - "offset": 0, - "slot": "0" - }, - { - "label": "expiration", - "type": "t_uint32", - "offset": 0, - "slot": "1" - }, - { - "label": "maxDuration", - "type": "t_uint32", - "offset": 4, - "slot": "1" - }, - { - "label": "minInterestRate", - "type": "t_uint16", - "offset": 8, - "slot": "1" - }, - { - "label": "collateralTokenAddress", - "type": "t_address", - "offset": 10, - "slot": "1" - }, - { - "label": "collateralTokenId", - "type": "t_uint256", - "offset": 0, - "slot": "2" - }, - { - "label": "maxPrincipalPerCollateralAmount", - "type": "t_uint256", - "offset": 0, - "slot": "3" - }, - { - "label": "collateralTokenType", - "type": "t_enum(CommitmentCollateralType)19656", - "offset": 0, - "slot": "4" - }, - { - "label": "lender", - "type": "t_address", - "offset": 1, - "slot": "4" - }, - { - "label": "marketId", - "type": "t_uint256", - "offset": 0, - "slot": "5" - }, - { - "label": "principalTokenAddress", - "type": "t_address", - "offset": 0, - "slot": "6" - } - ], - "numberOfBytes": "224" - }, - "t_struct(PoolRouteConfig)20596_storage": { - "label": "struct IUniswapPricingLibrary.PoolRouteConfig", - "members": [ - { - "label": "pool", - "type": "t_address", - "offset": 0, - "slot": "0" - }, - { - "label": "zeroForOne", - "type": "t_bool", - "offset": 20, - "slot": "0" - }, - { - "label": "twapInterval", - "type": "t_uint32", - "offset": 21, - "slot": "0" - }, - { - "label": "token0Decimals", - "type": "t_uint256", - "offset": 0, - "slot": "1" - }, - { - "label": "token1Decimals", - "type": "t_uint256", - "offset": 0, - "slot": "2" - } - ], - "numberOfBytes": "96" - }, - "t_struct(Set)2522_storage": { - "label": "struct EnumerableSetUpgradeable.Set", - "members": [ - { - "label": "_values", - "type": "t_array(t_bytes32)dyn_storage", - "offset": 0, - "slot": "0" - }, - { - "label": "_indexes", - "type": "t_mapping(t_bytes32,t_uint256)", - "offset": 0, - "slot": "1" - } - ], - "numberOfBytes": "64" - }, - "t_uint16": { - "label": "uint16", - "numberOfBytes": "2" - }, - "t_uint256": { - "label": "uint256", - "numberOfBytes": "32" - }, - "t_uint32": { - "label": "uint32", - "numberOfBytes": "4" - }, - "t_uint8": { - "label": "uint8", - "numberOfBytes": "1" - } - }, - "namespaces": {} - } - }, - "20811f1dfbba31cd2d615a2f305ca5e2792788d8fba22cdb575112a2652906ea": { - "address": "0x838F8e08C723CA4323cacD07D57777B27eAB3bD4", - "txHash": "0x4519c1f4d8b9ce63d0653eb941e7a6a5a4785c150528eb57d8ab62c199b6cbdc", + "txHash": "0x96d48a50155390a266e4a0a77a9c909906d12a15d922e0245ec2684571e8fe85", "layout": { "solcVersion": "0.8.11", "storage": [ diff --git a/packages/contracts/deployments/mainnet/.migrations.json b/packages/contracts/deployments/mainnet/.migrations.json index 82d684ab2..24d147b9d 100644 --- a/packages/contracts/deployments/mainnet/.migrations.json +++ b/packages/contracts/deployments/mainnet/.migrations.json @@ -35,5 +35,6 @@ "hypernative-oracle-mock:deploy": 1736787881, "lender-groups:upgrade": 1736788617, "validate-deployments": 1736794521, - "lender-commitment-forwarder:extensions:flash-swap-rollover:deploy": 1741031281 + "lender-commitment-forwarder:extensions:flash-swap-rollover:deploy": 1741031281, + "lender-commitment-forwarder:v2:deploy": 1743709093 } \ No newline at end of file diff --git a/packages/contracts/deployments/mainnet/LenderCommitmentForwarderV2.json b/packages/contracts/deployments/mainnet/LenderCommitmentForwarderV2.json new file mode 100644 index 000000000..8fc2d1281 --- /dev/null +++ b/packages/contracts/deployments/mainnet/LenderCommitmentForwarderV2.json @@ -0,0 +1,1107 @@ +{ + "address": "0x48EA70BCe76FE2F0c79B29Bf852a1DCF957982aa", + "abi": [ + { + "type": "constructor", + "stateMutability": "undefined", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_tellerV2" + }, + { + "type": "address", + "name": "_marketRegistry" + }, + { + "type": "address", + "name": "_uniswapV3Factory" + } + ] + }, + { + "type": "error", + "name": "InsufficientBorrowerCollateral", + "inputs": [ + { + "type": "uint256", + "name": "required" + }, + { + "type": "uint256", + "name": "actual" + } + ] + }, + { + "type": "error", + "name": "InsufficientCommitmentAllocation", + "inputs": [ + { + "type": "uint256", + "name": "allocated" + }, + { + "type": "uint256", + "name": "requested" + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "CreatedCommitment", + "inputs": [ + { + "type": "uint256", + "name": "commitmentId", + "indexed": true + }, + { + "type": "address", + "name": "lender", + "indexed": false + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "lendingToken", + "indexed": false + }, + { + "type": "uint256", + "name": "tokenAmount", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "DeletedCommitment", + "inputs": [ + { + "type": "uint256", + "name": "commitmentId", + "indexed": true + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ExercisedCommitment", + "inputs": [ + { + "type": "uint256", + "name": "commitmentId", + "indexed": true + }, + { + "type": "address", + "name": "borrower", + "indexed": false + }, + { + "type": "uint256", + "name": "tokenAmount", + "indexed": false + }, + { + "type": "uint256", + "name": "bidId", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ExtensionAdded", + "inputs": [ + { + "type": "address", + "name": "extension", + "indexed": false + }, + { + "type": "address", + "name": "sender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "ExtensionRevoked", + "inputs": [ + { + "type": "address", + "name": "extension", + "indexed": false + }, + { + "type": "address", + "name": "sender", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "Initialized", + "inputs": [ + { + "type": "uint8", + "name": "version", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UpdatedCommitment", + "inputs": [ + { + "type": "uint256", + "name": "commitmentId", + "indexed": true + }, + { + "type": "address", + "name": "lender", + "indexed": false + }, + { + "type": "uint256", + "name": "marketId", + "indexed": false + }, + { + "type": "address", + "name": "lendingToken", + "indexed": false + }, + { + "type": "uint256", + "name": "tokenAmount", + "indexed": false + } + ] + }, + { + "type": "event", + "anonymous": false, + "name": "UpdatedCommitmentBorrowers", + "inputs": [ + { + "type": "uint256", + "name": "commitmentId", + "indexed": true + } + ] + }, + { + "type": "function", + "name": "_marketRegistry", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "_tellerV2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "acceptCommitment", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "uint16", + "name": "_interestRate" + }, + { + "type": "uint32", + "name": "_loanDuration" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "bidId" + } + ] + }, + { + "type": "function", + "name": "acceptCommitmentWithProof", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "uint16", + "name": "_interestRate" + }, + { + "type": "uint32", + "name": "_loanDuration" + }, + { + "type": "bytes32[]", + "name": "_merkleProof" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "bidId" + } + ] + }, + { + "type": "function", + "name": "acceptCommitmentWithRecipient", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "address", + "name": "_recipient" + }, + { + "type": "uint16", + "name": "_interestRate" + }, + { + "type": "uint32", + "name": "_loanDuration" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "bidId" + } + ] + }, + { + "type": "function", + "name": "acceptCommitmentWithRecipientAndProof", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + }, + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_collateralAmount" + }, + { + "type": "uint256", + "name": "_collateralTokenId" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "address", + "name": "_recipient" + }, + { + "type": "uint16", + "name": "_interestRate" + }, + { + "type": "uint32", + "name": "_loanDuration" + }, + { + "type": "bytes32[]", + "name": "_merkleProof" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "bidId" + } + ] + }, + { + "type": "function", + "name": "addCommitmentBorrowers", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + }, + { + "type": "address[]", + "name": "_borrowerAddressList" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "addExtension", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "extension" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "commitmentPrincipalAccepted", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "commitments", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "maxPrincipal" + }, + { + "type": "uint32", + "name": "expiration" + }, + { + "type": "uint32", + "name": "maxDuration" + }, + { + "type": "uint16", + "name": "minInterestRate" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "collateralTokenId" + }, + { + "type": "uint256", + "name": "maxPrincipalPerCollateralAmount" + }, + { + "type": "uint8", + "name": "collateralTokenType" + }, + { + "type": "address", + "name": "lender" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "address", + "name": "principalTokenAddress" + } + ] + }, + { + "type": "function", + "name": "createCommitmentWithUniswap", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "tuple", + "name": "_commitment", + "components": [ + { + "type": "uint256", + "name": "maxPrincipal" + }, + { + "type": "uint32", + "name": "expiration" + }, + { + "type": "uint32", + "name": "maxDuration" + }, + { + "type": "uint16", + "name": "minInterestRate" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "collateralTokenId" + }, + { + "type": "uint256", + "name": "maxPrincipalPerCollateralAmount" + }, + { + "type": "uint8", + "name": "collateralTokenType" + }, + { + "type": "address", + "name": "lender" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "address", + "name": "principalTokenAddress" + } + ] + }, + { + "type": "address[]", + "name": "_borrowerAddressList" + }, + { + "type": "tuple[]", + "name": "_poolRoutes", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + }, + { + "type": "uint16", + "name": "_poolOracleLtvRatio" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "commitmentId_" + } + ] + }, + { + "type": "function", + "name": "deleteCommitment", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "getAllCommitmentUniswapPoolRoutes", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "commitmentId" + } + ], + "outputs": [ + { + "type": "tuple[]", + "name": "", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ] + }, + { + "type": "function", + "name": "getCommitmentAcceptedPrincipal", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCommitmentBorrowers", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [ + { + "type": "address[]", + "name": "borrowers_" + } + ] + }, + { + "type": "function", + "name": "getCommitmentCollateralTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCommitmentLender", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCommitmentMarketId", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCommitmentMaxPrincipal", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCommitmentPoolOracleLtvRatio", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "commitmentId" + } + ], + "outputs": [ + { + "type": "uint16", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCommitmentPrincipalTokenAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getCommitmentUniswapPoolRoute", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "commitmentId" + }, + { + "type": "uint256", + "name": "index" + } + ], + "outputs": [ + { + "type": "tuple", + "name": "", + "components": [ + { + "type": "address", + "name": "pool" + }, + { + "type": "bool", + "name": "zeroForOne" + }, + { + "type": "uint32", + "name": "twapInterval" + }, + { + "type": "uint256", + "name": "token0Decimals" + }, + { + "type": "uint256", + "name": "token1Decimals" + } + ] + } + ] + }, + { + "type": "function", + "name": "getMarketRegistry", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getRequiredCollateral", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_principalAmount" + }, + { + "type": "uint256", + "name": "_maxPrincipalPerCollateralAmount" + }, + { + "type": "uint8", + "name": "_collateralTokenType" + } + ], + "outputs": [ + { + "type": "uint256", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getTellerV2", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getTellerV2MarketOwner", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "marketId" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "getUniswapV3PoolAddress", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "_principalTokenAddress" + }, + { + "type": "address", + "name": "_collateralTokenAddress" + }, + { + "type": "uint24", + "name": "_uniswapPoolFee" + } + ], + "outputs": [ + { + "type": "address", + "name": "" + } + ] + }, + { + "type": "function", + "name": "hasExtension", + "constant": true, + "stateMutability": "view", + "payable": false, + "inputs": [ + { + "type": "address", + "name": "account" + }, + { + "type": "address", + "name": "extension" + } + ], + "outputs": [ + { + "type": "bool", + "name": "" + } + ] + }, + { + "type": "function", + "name": "removeCommitmentBorrowers", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + }, + { + "type": "address[]", + "name": "_borrowerAddressList" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "revokeExtension", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "address", + "name": "extension" + } + ], + "outputs": [] + }, + { + "type": "function", + "name": "updateCommitment", + "constant": false, + "payable": false, + "inputs": [ + { + "type": "uint256", + "name": "_commitmentId" + }, + { + "type": "tuple", + "name": "_commitment", + "components": [ + { + "type": "uint256", + "name": "maxPrincipal" + }, + { + "type": "uint32", + "name": "expiration" + }, + { + "type": "uint32", + "name": "maxDuration" + }, + { + "type": "uint16", + "name": "minInterestRate" + }, + { + "type": "address", + "name": "collateralTokenAddress" + }, + { + "type": "uint256", + "name": "collateralTokenId" + }, + { + "type": "uint256", + "name": "maxPrincipalPerCollateralAmount" + }, + { + "type": "uint8", + "name": "collateralTokenType" + }, + { + "type": "address", + "name": "lender" + }, + { + "type": "uint256", + "name": "marketId" + }, + { + "type": "address", + "name": "principalTokenAddress" + } + ] + } + ], + "outputs": [] + } + ], + "transactionHash": "0xb07c28093b21124a67581081bfe249db62abbce021982702d82e3728320cc61b", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "blockHash": null, + "blockNumber": null + }, + "numDeployments": 1, + "implementation": "0xC764a44Faa62dB04310e0c8eA8d56FDC411e3e31" +} \ No newline at end of file diff --git a/packages/contracts/deployments/mainnet/UniswapPricingLibraryV2.json b/packages/contracts/deployments/mainnet/UniswapPricingLibraryV2.json new file mode 100644 index 000000000..fb4b9dbe6 --- /dev/null +++ b/packages/contracts/deployments/mainnet/UniswapPricingLibraryV2.json @@ -0,0 +1,133 @@ +{ + "address": "0x62C4D65a8240785b7240bf5A8e21E16474D757F1", + "abi": [ + { + "inputs": [ + { + "components": [ + { + "internalType": "address", + "name": "pool", + "type": "address" + }, + { + "internalType": "bool", + "name": "zeroForOne", + "type": "bool" + }, + { + "internalType": "uint32", + "name": "twapInterval", + "type": "uint32" + }, + { + "internalType": "uint256", + "name": "token0Decimals", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "token1Decimals", + "type": "uint256" + } + ], + "internalType": "struct IUniswapPricingLibrary.PoolRouteConfig", + "name": "_poolRouteConfig", + "type": "tuple" + } + ], + "name": "getUniswapPriceRatioForPool", + "outputs": [ + { + "internalType": "uint256", + "name": "priceRatio", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "components": [ + { + "internalType": "address", + "name": "pool", + "type": "address" + }, + { + "internalType": "bool", + "name": "zeroForOne", + "type": "bool" + }, + { + "internalType": "uint32", + "name": "twapInterval", + "type": "uint32" + }, + { + "internalType": "uint256", + "name": "token0Decimals", + "type": "uint256" + }, + { + "internalType": "uint256", + "name": "token1Decimals", + "type": "uint256" + } + ], + "internalType": "struct IUniswapPricingLibrary.PoolRouteConfig[]", + "name": "poolRoutes", + "type": "tuple[]" + } + ], + "name": "getUniswapPriceRatioForPoolRoutes", + "outputs": [ + { + "internalType": "uint256", + "name": "priceRatio", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + } + ], + "transactionHash": "0x51e8ce10ec020602feb9152217f3464eccc1dfeb6e2d473af6feab6c291e4931", + "receipt": { + "to": null, + "from": "0xD9B023522CeCe02251d877bb0EB4f06fDe6F98E6", + "contractAddress": "0x62C4D65a8240785b7240bf5A8e21E16474D757F1", + "transactionIndex": 64, + "gasUsed": "928175", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xf18701ad66238bf24a3c2d5cba1195b550a91e7ea1401a32c8b8979a4f725b91", + "transactionHash": "0x51e8ce10ec020602feb9152217f3464eccc1dfeb6e2d473af6feab6c291e4931", + "logs": [], + "blockNumber": 22190513, + "cumulativeGasUsed": "3907900", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "c4af209b4dcb1fbdc66baa1eb36588ed", + "metadata": "{\"compiler\":{\"version\":\"0.8.11+commit.d7f03943\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"pool\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"zeroForOne\",\"type\":\"bool\"},{\"internalType\":\"uint32\",\"name\":\"twapInterval\",\"type\":\"uint32\"},{\"internalType\":\"uint256\",\"name\":\"token0Decimals\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"token1Decimals\",\"type\":\"uint256\"}],\"internalType\":\"struct IUniswapPricingLibrary.PoolRouteConfig\",\"name\":\"_poolRouteConfig\",\"type\":\"tuple\"}],\"name\":\"getUniswapPriceRatioForPool\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatio\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"components\":[{\"internalType\":\"address\",\"name\":\"pool\",\"type\":\"address\"},{\"internalType\":\"bool\",\"name\":\"zeroForOne\",\"type\":\"bool\"},{\"internalType\":\"uint32\",\"name\":\"twapInterval\",\"type\":\"uint32\"},{\"internalType\":\"uint256\",\"name\":\"token0Decimals\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"token1Decimals\",\"type\":\"uint256\"}],\"internalType\":\"struct IUniswapPricingLibrary.PoolRouteConfig[]\",\"name\":\"poolRoutes\",\"type\":\"tuple[]\"}],\"name\":\"getUniswapPriceRatioForPoolRoutes\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"priceRatio\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/libraries/UniswapPricingLibraryV2.sol\":\"UniswapPricingLibraryV2\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../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 Throws if called by any account other than the owner.\\n */\\n modifier onlyOwner() {\\n _checkOwner();\\n _;\\n }\\n\\n /**\\n * @dev Returns the address of the current owner.\\n */\\n function owner() public view virtual returns (address) {\\n return _owner;\\n }\\n\\n /**\\n * @dev Throws if the sender is not the owner.\\n */\\n function _checkOwner() internal view virtual {\\n require(owner() == _msgSender(), \\\"Ownable: caller is not the owner\\\");\\n }\\n\\n /**\\n * @dev Leaves the contract without owner. It will not be possible to call\\n * `onlyOwner` functions anymore. Can only be called by the current owner.\\n *\\n * NOTE: Renouncing ownership will leave the contract without an owner,\\n * thereby removing any functionality that is only available to the owner.\\n */\\n function renounceOwnership() public virtual onlyOwner {\\n _transferOwnership(address(0));\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Can only be called by the current owner.\\n */\\n function transferOwnership(address newOwner) public virtual onlyOwner {\\n require(newOwner != address(0), \\\"Ownable: new owner is the zero address\\\");\\n _transferOwnership(newOwner);\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Internal function without access restriction.\\n */\\n function _transferOwnership(address newOwner) internal virtual {\\n address oldOwner = _owner;\\n _owner = newOwner;\\n emit OwnershipTransferred(oldOwner, newOwner);\\n }\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[49] private __gap;\\n}\\n\",\"keccak256\":\"0x247c62047745915c0af6b955470a72d1696ebad4352d7d3011aef1a2463cd888\",\"license\":\"MIT\"},\"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.8.1) (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.\\n *\\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\\n * constructor.\\n *\\n * Emits an {Initialized} event.\\n */\\n modifier initializer() {\\n bool isTopLevelCall = !_initializing;\\n require(\\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\\n \\\"Initializable: contract is already initialized\\\"\\n );\\n _initialized = 1;\\n if (isTopLevelCall) {\\n _initializing = true;\\n }\\n _;\\n if (isTopLevelCall) {\\n _initializing = false;\\n emit Initialized(1);\\n }\\n }\\n\\n /**\\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\\n * used to initialize parent contracts.\\n *\\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\\n * are added through upgrades and that require initialization.\\n *\\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\\n * cannot be nested. If one is invoked in the context of another, execution will revert.\\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 * WARNING: setting the version to 255 will prevent any future reinitialization.\\n *\\n * Emits an {Initialized} event.\\n */\\n modifier reinitializer(uint8 version) {\\n require(!_initializing && _initialized < version, \\\"Initializable: contract is already initialized\\\");\\n _initialized = version;\\n _initializing = true;\\n _;\\n _initializing = false;\\n emit Initialized(version);\\n }\\n\\n /**\\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\\n */\\n modifier onlyInitializing() {\\n require(_initializing, \\\"Initializable: contract is not initializing\\\");\\n _;\\n }\\n\\n /**\\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\\n * through proxies.\\n *\\n * Emits an {Initialized} event the first time it is successfully executed.\\n */\\n function _disableInitializers() internal virtual {\\n require(!_initializing, \\\"Initializable: contract is initializing\\\");\\n if (_initialized < type(uint8).max) {\\n _initialized = type(uint8).max;\\n emit Initialized(type(uint8).max);\\n }\\n }\\n\\n /**\\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\\n */\\n function _getInitializedVersion() internal view returns (uint8) {\\n return _initialized;\\n }\\n\\n /**\\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\\n */\\n function _isInitializing() internal view returns (bool) {\\n return _initializing;\\n }\\n}\\n\",\"keccak256\":\"0x037c334add4b033ad3493038c25be1682d78c00992e1acb0e2795caff3925271\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0x4e733d3164f73f461eaf9d8087a7ad1ea180bdc8ba0d3d61b0e1ae16d8e63dff\",\"license\":\"MIT\"},\"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../IERC20Upgradeable.sol\\\";\\n\\n/**\\n * @dev Interface for the optional metadata functions from the ERC20 standard.\\n *\\n * _Available since v4.1._\\n */\\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() external view returns (string memory);\\n\\n /**\\n * @dev Returns the symbol of the token.\\n */\\n function symbol() external view returns (string memory);\\n\\n /**\\n * @dev Returns the decimals places of the token.\\n */\\n function decimals() external view returns (uint8);\\n}\\n\",\"keccak256\":\"0x605434219ebbe4653f703640f06969faa5a1d78f0bfef878e5ddbb1ca369ceeb\",\"license\":\"MIT\"},\"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.8.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 functionCallWithValue(target, data, 0, \\\"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 (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResultFromTarget(target, 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 (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\\n *\\n * _Available since v4.8._\\n */\\n function verifyCallResultFromTarget(\\n address target,\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n if (success) {\\n if (returndata.length == 0) {\\n // only check isContract if the call was successful and the return data is empty\\n // otherwise we already know that it was a contract\\n require(isContract(target), \\\"Address: call to non-contract\\\");\\n }\\n return returndata;\\n } else {\\n _revert(returndata, errorMessage);\\n }\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\\n * revert reason or 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 _revert(returndata, errorMessage);\\n }\\n }\\n\\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\\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\",\"keccak256\":\"0x2edcb41c121abc510932e8d83ff8b82cf9cdde35e7c297622f5c29ef0af25183\",\"license\":\"MIT\"},\"@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\",\"keccak256\":\"0x963ea7f0b48b032eef72fe3a7582edf78408d6f834115b9feadd673a4d5bd149\",\"license\":\"MIT\"},\"@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/MerkleProof.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev These functions deal with verification of Merkle Tree proofs.\\n *\\n * The tree and the proofs can be generated using our\\n * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].\\n * You will find a quickstart guide in the readme.\\n *\\n * WARNING: You should avoid using leaf values that are 64 bytes long prior to\\n * hashing, or use a hash function other than keccak256 for hashing leaves.\\n * This is because the concatenation of a sorted pair of internal nodes in\\n * the merkle tree could be reinterpreted as a leaf value.\\n * OpenZeppelin's JavaScript library generates merkle trees that are safe\\n * against this attack out of the box.\\n */\\nlibrary MerkleProofUpgradeable {\\n /**\\n * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree\\n * defined by `root`. For this, a `proof` must be provided, containing\\n * sibling hashes on the branch from the leaf to the root of the tree. Each\\n * pair of leaves and each pair of pre-images are assumed to be sorted.\\n */\\n function verify(\\n bytes32[] memory proof,\\n bytes32 root,\\n bytes32 leaf\\n ) internal pure returns (bool) {\\n return processProof(proof, leaf) == root;\\n }\\n\\n /**\\n * @dev Calldata version of {verify}\\n *\\n * _Available since v4.7._\\n */\\n function verifyCalldata(\\n bytes32[] calldata proof,\\n bytes32 root,\\n bytes32 leaf\\n ) internal pure returns (bool) {\\n return processProofCalldata(proof, leaf) == root;\\n }\\n\\n /**\\n * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up\\n * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt\\n * hash matches the root of the tree. When processing the proof, the pairs\\n * of leafs & pre-images are assumed to be sorted.\\n *\\n * _Available since v4.4._\\n */\\n function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {\\n bytes32 computedHash = leaf;\\n for (uint256 i = 0; i < proof.length; i++) {\\n computedHash = _hashPair(computedHash, proof[i]);\\n }\\n return computedHash;\\n }\\n\\n /**\\n * @dev Calldata version of {processProof}\\n *\\n * _Available since v4.7._\\n */\\n function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {\\n bytes32 computedHash = leaf;\\n for (uint256 i = 0; i < proof.length; i++) {\\n computedHash = _hashPair(computedHash, proof[i]);\\n }\\n return computedHash;\\n }\\n\\n /**\\n * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by\\n * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.\\n *\\n * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.\\n *\\n * _Available since v4.7._\\n */\\n function multiProofVerify(\\n bytes32[] memory proof,\\n bool[] memory proofFlags,\\n bytes32 root,\\n bytes32[] memory leaves\\n ) internal pure returns (bool) {\\n return processMultiProof(proof, proofFlags, leaves) == root;\\n }\\n\\n /**\\n * @dev Calldata version of {multiProofVerify}\\n *\\n * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.\\n *\\n * _Available since v4.7._\\n */\\n function multiProofVerifyCalldata(\\n bytes32[] calldata proof,\\n bool[] calldata proofFlags,\\n bytes32 root,\\n bytes32[] memory leaves\\n ) internal pure returns (bool) {\\n return processMultiProofCalldata(proof, proofFlags, leaves) == root;\\n }\\n\\n /**\\n * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction\\n * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another\\n * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false\\n * respectively.\\n *\\n * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree\\n * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the\\n * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).\\n *\\n * _Available since v4.7._\\n */\\n function processMultiProof(\\n bytes32[] memory proof,\\n bool[] memory proofFlags,\\n bytes32[] memory leaves\\n ) internal pure returns (bytes32 merkleRoot) {\\n // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by\\n // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\\n // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\\n // the merkle tree.\\n uint256 leavesLen = leaves.length;\\n uint256 totalHashes = proofFlags.length;\\n\\n // Check proof validity.\\n require(leavesLen + proof.length - 1 == totalHashes, \\\"MerkleProof: invalid multiproof\\\");\\n\\n // The xxxPos values are \\\"pointers\\\" to the next value to consume in each array. All accesses are done using\\n // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \\\"pop\\\".\\n bytes32[] memory hashes = new bytes32[](totalHashes);\\n uint256 leafPos = 0;\\n uint256 hashPos = 0;\\n uint256 proofPos = 0;\\n // At each step, we compute the next hash using two values:\\n // - a value from the \\\"main queue\\\". If not all leaves have been consumed, we get the next leaf, otherwise we\\n // get the next hash.\\n // - depending on the flag, either another value for the \\\"main queue\\\" (merging branches) or an element from the\\n // `proof` array.\\n for (uint256 i = 0; i < totalHashes; i++) {\\n bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\\n bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];\\n hashes[i] = _hashPair(a, b);\\n }\\n\\n if (totalHashes > 0) {\\n return hashes[totalHashes - 1];\\n } else if (leavesLen > 0) {\\n return leaves[0];\\n } else {\\n return proof[0];\\n }\\n }\\n\\n /**\\n * @dev Calldata version of {processMultiProof}.\\n *\\n * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.\\n *\\n * _Available since v4.7._\\n */\\n function processMultiProofCalldata(\\n bytes32[] calldata proof,\\n bool[] calldata proofFlags,\\n bytes32[] memory leaves\\n ) internal pure returns (bytes32 merkleRoot) {\\n // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by\\n // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the\\n // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of\\n // the merkle tree.\\n uint256 leavesLen = leaves.length;\\n uint256 totalHashes = proofFlags.length;\\n\\n // Check proof validity.\\n require(leavesLen + proof.length - 1 == totalHashes, \\\"MerkleProof: invalid multiproof\\\");\\n\\n // The xxxPos values are \\\"pointers\\\" to the next value to consume in each array. All accesses are done using\\n // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's \\\"pop\\\".\\n bytes32[] memory hashes = new bytes32[](totalHashes);\\n uint256 leafPos = 0;\\n uint256 hashPos = 0;\\n uint256 proofPos = 0;\\n // At each step, we compute the next hash using two values:\\n // - a value from the \\\"main queue\\\". If not all leaves have been consumed, we get the next leaf, otherwise we\\n // get the next hash.\\n // - depending on the flag, either another value for the \\\"main queue\\\" (merging branches) or an element from the\\n // `proof` array.\\n for (uint256 i = 0; i < totalHashes; i++) {\\n bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];\\n bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];\\n hashes[i] = _hashPair(a, b);\\n }\\n\\n if (totalHashes > 0) {\\n return hashes[totalHashes - 1];\\n } else if (leavesLen > 0) {\\n return leaves[0];\\n } else {\\n return proof[0];\\n }\\n }\\n\\n function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {\\n return a < b ? _efficientHash(a, b) : _efficientHash(b, a);\\n }\\n\\n function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n mstore(0x00, a)\\n mstore(0x20, b)\\n value := keccak256(0x00, 0x40)\\n }\\n }\\n}\\n\",\"keccak256\":\"0x1741ea24897cdf435d3a476e9d9280b8be58a435dacb6997d54a2aa657446e5a\",\"license\":\"MIT\"},\"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.8.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 MathUpgradeable {\\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 //\\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)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\\n //\\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\\n // \\u2192 `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\\n // \\u2192 `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\\n //\\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\\n uint256 result = 1 << (log2(a) >> 1);\\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 unchecked {\\n uint256 result = sqrt(a);\\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 2, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 128;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 64;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 32;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 16;\\n }\\n if (value >> 8 > 0) {\\n value >>= 8;\\n result += 8;\\n }\\n if (value >> 4 > 0) {\\n value >>= 4;\\n result += 4;\\n }\\n if (value >> 2 > 0) {\\n value >>= 2;\\n result += 2;\\n }\\n if (value >> 1 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log2(value);\\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 10, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >= 10**64) {\\n value /= 10**64;\\n result += 64;\\n }\\n if (value >= 10**32) {\\n value /= 10**32;\\n result += 32;\\n }\\n if (value >= 10**16) {\\n value /= 10**16;\\n result += 16;\\n }\\n if (value >= 10**8) {\\n value /= 10**8;\\n result += 8;\\n }\\n if (value >= 10**4) {\\n value /= 10**4;\\n result += 4;\\n }\\n if (value >= 10**2) {\\n value /= 10**2;\\n result += 2;\\n }\\n if (value >= 10**1) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log10(value);\\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 256, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n *\\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\\n */\\n function log256(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 16;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 8;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 4;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 2;\\n }\\n if (value >> 8 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log256(value);\\n return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\\n }\\n }\\n}\\n\",\"keccak256\":\"0xc1bd5b53319c68f84e3becd75694d941e8f4be94049903232cd8bc7c535aaa5a\",\"license\":\"MIT\"},\"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)\\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Library for managing\\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\\n * types.\\n *\\n * Sets have the following properties:\\n *\\n * - Elements are added, removed, and checked for existence in constant time\\n * (O(1)).\\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\\n *\\n * ```\\n * contract Example {\\n * // Add the library methods\\n * using EnumerableSet for EnumerableSet.AddressSet;\\n *\\n * // Declare a set state variable\\n * EnumerableSet.AddressSet private mySet;\\n * }\\n * ```\\n *\\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\\n * and `uint256` (`UintSet`) are supported.\\n *\\n * [WARNING]\\n * ====\\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\\n * unusable.\\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\\n *\\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\\n * array of EnumerableSet.\\n * ====\\n */\\nlibrary EnumerableSetUpgradeable {\\n // To implement this library for multiple types with as little code\\n // repetition as possible, we write it in terms of a generic Set type with\\n // bytes32 values.\\n // The Set implementation uses private functions, and user-facing\\n // implementations (such as AddressSet) are just wrappers around the\\n // underlying Set.\\n // This means that we can only create new EnumerableSets for types that fit\\n // in bytes32.\\n\\n struct Set {\\n // Storage of set values\\n bytes32[] _values;\\n // Position of the value in the `values` array, plus 1 because index 0\\n // means a value is not in the set.\\n mapping(bytes32 => uint256) _indexes;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function _add(Set storage set, bytes32 value) private returns (bool) {\\n if (!_contains(set, value)) {\\n set._values.push(value);\\n // The value is stored at length-1, but we add 1 to all indexes\\n // and use 0 as a sentinel value\\n set._indexes[value] = set._values.length;\\n return true;\\n } else {\\n return false;\\n }\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function _remove(Set storage set, bytes32 value) private returns (bool) {\\n // We read and store the value's index to prevent multiple reads from the same storage slot\\n uint256 valueIndex = set._indexes[value];\\n\\n if (valueIndex != 0) {\\n // Equivalent to contains(set, value)\\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\\n // the array, and then remove the last element (sometimes called as 'swap and pop').\\n // This modifies the order of the array, as noted in {at}.\\n\\n uint256 toDeleteIndex = valueIndex - 1;\\n uint256 lastIndex = set._values.length - 1;\\n\\n if (lastIndex != toDeleteIndex) {\\n bytes32 lastValue = set._values[lastIndex];\\n\\n // Move the last value to the index where the value to delete is\\n set._values[toDeleteIndex] = lastValue;\\n // Update the index for the moved value\\n set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\\n }\\n\\n // Delete the slot where the moved value was stored\\n set._values.pop();\\n\\n // Delete the index for the deleted slot\\n delete set._indexes[value];\\n\\n return true;\\n } else {\\n return false;\\n }\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\\n return set._indexes[value] != 0;\\n }\\n\\n /**\\n * @dev Returns the number of values on the set. O(1).\\n */\\n function _length(Set storage set) private view returns (uint256) {\\n return set._values.length;\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\\n return set._values[index];\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function _values(Set storage set) private view returns (bytes32[] memory) {\\n return set._values;\\n }\\n\\n // Bytes32Set\\n\\n struct Bytes32Set {\\n Set _inner;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\\n return _add(set._inner, value);\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\\n return _remove(set._inner, value);\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\\n return _contains(set._inner, value);\\n }\\n\\n /**\\n * @dev Returns the number of values in the set. O(1).\\n */\\n function length(Bytes32Set storage set) internal view returns (uint256) {\\n return _length(set._inner);\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\\n return _at(set._inner, index);\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\\n bytes32[] memory store = _values(set._inner);\\n bytes32[] memory result;\\n\\n /// @solidity memory-safe-assembly\\n assembly {\\n result := store\\n }\\n\\n return result;\\n }\\n\\n // AddressSet\\n\\n struct AddressSet {\\n Set _inner;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function add(AddressSet storage set, address value) internal returns (bool) {\\n return _add(set._inner, bytes32(uint256(uint160(value))));\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function remove(AddressSet storage set, address value) internal returns (bool) {\\n return _remove(set._inner, bytes32(uint256(uint160(value))));\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function contains(AddressSet storage set, address value) internal view returns (bool) {\\n return _contains(set._inner, bytes32(uint256(uint160(value))));\\n }\\n\\n /**\\n * @dev Returns the number of values in the set. O(1).\\n */\\n function length(AddressSet storage set) internal view returns (uint256) {\\n return _length(set._inner);\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\\n return address(uint160(uint256(_at(set._inner, index))));\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function values(AddressSet storage set) internal view returns (address[] memory) {\\n bytes32[] memory store = _values(set._inner);\\n address[] memory result;\\n\\n /// @solidity memory-safe-assembly\\n assembly {\\n result := store\\n }\\n\\n return result;\\n }\\n\\n // UintSet\\n\\n struct UintSet {\\n Set _inner;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function add(UintSet storage set, uint256 value) internal returns (bool) {\\n return _add(set._inner, bytes32(value));\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\\n return _remove(set._inner, bytes32(value));\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\\n return _contains(set._inner, bytes32(value));\\n }\\n\\n /**\\n * @dev Returns the number of values in the set. O(1).\\n */\\n function length(UintSet storage set) internal view returns (uint256) {\\n return _length(set._inner);\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\\n return uint256(_at(set._inner, index));\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function values(UintSet storage set) internal view returns (uint256[] memory) {\\n bytes32[] memory store = _values(set._inner);\\n uint256[] memory result;\\n\\n /// @solidity memory-safe-assembly\\n assembly {\\n result := store\\n }\\n\\n return result;\\n }\\n}\\n\",\"keccak256\":\"0x4807db844a856813048b5af81a764fdd25a0ae8876a3132593e8d21ddc6b607c\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/IERC20.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 IERC20 {\\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\",\"keccak256\":\"0x9750c6b834f7b43000631af5cc30001c5f547b3ceb3635488f140f60e897ea6b\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/math/Math.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.8.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 //\\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)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\\n //\\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\\n // \\u2192 `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\\n // \\u2192 `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\\n //\\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\\n uint256 result = 1 << (log2(a) >> 1);\\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 unchecked {\\n uint256 result = sqrt(a);\\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 2, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 128;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 64;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 32;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 16;\\n }\\n if (value >> 8 > 0) {\\n value >>= 8;\\n result += 8;\\n }\\n if (value >> 4 > 0) {\\n value >>= 4;\\n result += 4;\\n }\\n if (value >> 2 > 0) {\\n value >>= 2;\\n result += 2;\\n }\\n if (value >> 1 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log2(value);\\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 10, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >= 10**64) {\\n value /= 10**64;\\n result += 64;\\n }\\n if (value >= 10**32) {\\n value /= 10**32;\\n result += 32;\\n }\\n if (value >= 10**16) {\\n value /= 10**16;\\n result += 16;\\n }\\n if (value >= 10**8) {\\n value /= 10**8;\\n result += 8;\\n }\\n if (value >= 10**4) {\\n value /= 10**4;\\n result += 4;\\n }\\n if (value >= 10**2) {\\n value /= 10**2;\\n result += 2;\\n }\\n if (value >= 10**1) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log10(value);\\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 256, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n *\\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\\n */\\n function log256(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 16;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 8;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 4;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 2;\\n }\\n if (value >> 8 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log256(value);\\n return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\\n }\\n }\\n}\\n\",\"keccak256\":\"0xa1e8e83cd0087785df04ac79fb395d9f3684caeaf973d9e2c71caef723a3a5d6\",\"license\":\"MIT\"},\"contracts/interfaces/IUniswapPricingLibrary.sol\":{\"content\":\"// SPDX-Licence-Identifier: MIT\\npragma solidity >=0.8.0 <0.9.0;\\n\\ninterface IUniswapPricingLibrary {\\n \\n\\n struct PoolRouteConfig {\\n address pool;\\n bool zeroForOne;\\n uint32 twapInterval;\\n uint256 token0Decimals;\\n uint256 token1Decimals;\\n } \\n\\n\\n\\n function getUniswapPriceRatioForPoolRoutes(\\n PoolRouteConfig[] memory poolRoutes\\n ) external view returns (uint256 priceRatio);\\n\\n\\n function getUniswapPriceRatioForPool(\\n PoolRouteConfig memory poolRoute\\n ) external view returns (uint256 priceRatio);\\n\\n}\\n\",\"keccak256\":\"0xaac4c07c82618cc01b41d56d57b52cf134afdc2220115ccc1744adfc475c2583\"},\"contracts/interfaces/uniswap/IUniswapV3Pool.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-2.0-or-later\\npragma solidity >=0.5.0;\\n\\nimport \\\"./pool/IUniswapV3PoolImmutables.sol\\\";\\nimport \\\"./pool/IUniswapV3PoolState.sol\\\";\\nimport \\\"./pool/IUniswapV3PoolDerivedState.sol\\\";\\nimport \\\"./pool/IUniswapV3PoolActions.sol\\\";\\nimport \\\"./pool/IUniswapV3PoolOwnerActions.sol\\\";\\nimport \\\"./pool/IUniswapV3PoolEvents.sol\\\";\\n\\n/// @title The interface for a Uniswap V3 Pool\\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\\n/// to the ERC20 specification\\n/// @dev The pool interface is broken up into many smaller pieces\\ninterface IUniswapV3Pool is\\n IUniswapV3PoolImmutables,\\n IUniswapV3PoolState,\\n IUniswapV3PoolDerivedState,\\n IUniswapV3PoolActions,\\n IUniswapV3PoolOwnerActions,\\n IUniswapV3PoolEvents\\n{\\n\\n}\\n\",\"keccak256\":\"0xb3ab192db0227b3253579f34b108af8c91c6b54bfe805fa59f11abdcb13e87fa\",\"license\":\"GPL-2.0-or-later\"},\"contracts/interfaces/uniswap/pool/IUniswapV3PoolActions.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-2.0-or-later\\npragma solidity >=0.5.0;\\n\\n/// @title Permissionless pool actions\\n/// @notice Contains pool methods that can be called by anyone\\ninterface IUniswapV3PoolActions {\\n /// @notice Sets the initial price for the pool\\n /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\\n /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\\n function initialize(uint160 sqrtPriceX96) external;\\n\\n /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\\n /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\\n /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\\n /// on tickLower, tickUpper, the amount of liquidity, and the current price.\\n /// @param recipient The address for which the liquidity will be created\\n /// @param tickLower The lower tick of the position in which to add liquidity\\n /// @param tickUpper The upper tick of the position in which to add liquidity\\n /// @param amount The amount of liquidity to mint\\n /// @param data Any data that should be passed through to the callback\\n /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\\n /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\\n function mint(\\n address recipient,\\n int24 tickLower,\\n int24 tickUpper,\\n uint128 amount,\\n bytes calldata data\\n ) external returns (uint256 amount0, uint256 amount1);\\n\\n /// @notice Collects tokens owed to a position\\n /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\\n /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\\n /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\\n /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\\n /// @param recipient The address which should receive the fees collected\\n /// @param tickLower The lower tick of the position for which to collect fees\\n /// @param tickUpper The upper tick of the position for which to collect fees\\n /// @param amount0Requested How much token0 should be withdrawn from the fees owed\\n /// @param amount1Requested How much token1 should be withdrawn from the fees owed\\n /// @return amount0 The amount of fees collected in token0\\n /// @return amount1 The amount of fees collected in token1\\n function collect(\\n address recipient,\\n int24 tickLower,\\n int24 tickUpper,\\n uint128 amount0Requested,\\n uint128 amount1Requested\\n ) external returns (uint128 amount0, uint128 amount1);\\n\\n /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\\n /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\\n /// @dev Fees must be collected separately via a call to #collect\\n /// @param tickLower The lower tick of the position for which to burn liquidity\\n /// @param tickUpper The upper tick of the position for which to burn liquidity\\n /// @param amount How much liquidity to burn\\n /// @return amount0 The amount of token0 sent to the recipient\\n /// @return amount1 The amount of token1 sent to the recipient\\n function burn(int24 tickLower, int24 tickUpper, uint128 amount)\\n external\\n returns (uint256 amount0, uint256 amount1);\\n\\n /// @notice Swap token0 for token1, or token1 for token0\\n /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\\n /// @param recipient The address to receive the output of the swap\\n /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\\n /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\\n /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\\n /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\\n /// @param data Any data to be passed through to the callback\\n /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\\n /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\\n function swap(\\n address recipient,\\n bool zeroForOne,\\n int256 amountSpecified,\\n uint160 sqrtPriceLimitX96,\\n bytes calldata data\\n ) external returns (int256 amount0, int256 amount1);\\n\\n /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\\n /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\\n /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\\n /// with 0 amount{0,1} and sending the donation amount(s) from the callback\\n /// @param recipient The address which will receive the token0 and token1 amounts\\n /// @param amount0 The amount of token0 to send\\n /// @param amount1 The amount of token1 to send\\n /// @param data Any data to be passed through to the callback\\n function flash(\\n address recipient,\\n uint256 amount0,\\n uint256 amount1,\\n bytes calldata data\\n ) external;\\n\\n /// @notice Increase the maximum number of price and liquidity observations that this pool will store\\n /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\\n /// the input observationCardinalityNext.\\n /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\\n function increaseObservationCardinalityNext(\\n uint16 observationCardinalityNext\\n ) external;\\n}\\n\",\"keccak256\":\"0x0d71eeba27d612d047b327e34231360e4e0014d0241e791e5ad62fb40a1a73b3\",\"license\":\"GPL-2.0-or-later\"},\"contracts/interfaces/uniswap/pool/IUniswapV3PoolDerivedState.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-2.0-or-later\\npragma solidity >=0.5.0;\\n\\n/// @title Pool state that is not stored\\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\\n/// blockchain. The functions here may have variable gas costs.\\ninterface IUniswapV3PoolDerivedState {\\n /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\\n /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\\n /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\\n /// you must call it with secondsAgos = [3600, 0].\\n /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\\n /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\\n /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\\n /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\\n /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\\n /// timestamp\\n function observe(uint32[] calldata secondsAgos)\\n external\\n view\\n returns (\\n int56[] memory tickCumulatives,\\n uint160[] memory secondsPerLiquidityCumulativeX128s\\n );\\n\\n /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\\n /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\\n /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\\n /// snapshot is taken and the second snapshot is taken.\\n /// @param tickLower The lower tick of the range\\n /// @param tickUpper The upper tick of the range\\n /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\\n /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\\n /// @return secondsInside The snapshot of seconds per liquidity for the range\\n function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\\n external\\n view\\n returns (\\n int56 tickCumulativeInside,\\n uint160 secondsPerLiquidityInsideX128,\\n uint32 secondsInside\\n );\\n}\\n\",\"keccak256\":\"0x75a1cde36f8d8e785df6b61c2b87c9a25f1a7bf05567bd490f021113286c7966\",\"license\":\"GPL-2.0-or-later\"},\"contracts/interfaces/uniswap/pool/IUniswapV3PoolEvents.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-2.0-or-later\\npragma solidity >=0.5.0;\\n\\n/// @title Events emitted by a pool\\n/// @notice Contains all events emitted by the pool\\ninterface IUniswapV3PoolEvents {\\n /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\\n /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\\n /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\\n /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\\n event Initialize(uint160 sqrtPriceX96, int24 tick);\\n\\n /// @notice Emitted when liquidity is minted for a given position\\n /// @param sender The address that minted the liquidity\\n /// @param owner The owner of the position and recipient of any minted liquidity\\n /// @param tickLower The lower tick of the position\\n /// @param tickUpper The upper tick of the position\\n /// @param amount The amount of liquidity minted to the position range\\n /// @param amount0 How much token0 was required for the minted liquidity\\n /// @param amount1 How much token1 was required for the minted liquidity\\n event Mint(\\n address sender,\\n address indexed owner,\\n int24 indexed tickLower,\\n int24 indexed tickUpper,\\n uint128 amount,\\n uint256 amount0,\\n uint256 amount1\\n );\\n\\n /// @notice Emitted when fees are collected by the owner of a position\\n /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\\n /// @param owner The owner of the position for which fees are collected\\n /// @param tickLower The lower tick of the position\\n /// @param tickUpper The upper tick of the position\\n /// @param amount0 The amount of token0 fees collected\\n /// @param amount1 The amount of token1 fees collected\\n event Collect(\\n address indexed owner,\\n address recipient,\\n int24 indexed tickLower,\\n int24 indexed tickUpper,\\n uint128 amount0,\\n uint128 amount1\\n );\\n\\n /// @notice Emitted when a position's liquidity is removed\\n /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\\n /// @param owner The owner of the position for which liquidity is removed\\n /// @param tickLower The lower tick of the position\\n /// @param tickUpper The upper tick of the position\\n /// @param amount The amount of liquidity to remove\\n /// @param amount0 The amount of token0 withdrawn\\n /// @param amount1 The amount of token1 withdrawn\\n event Burn(\\n address indexed owner,\\n int24 indexed tickLower,\\n int24 indexed tickUpper,\\n uint128 amount,\\n uint256 amount0,\\n uint256 amount1\\n );\\n\\n /// @notice Emitted by the pool for any swaps between token0 and token1\\n /// @param sender The address that initiated the swap call, and that received the callback\\n /// @param recipient The address that received the output of the swap\\n /// @param amount0 The delta of the token0 balance of the pool\\n /// @param amount1 The delta of the token1 balance of the pool\\n /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\\n /// @param liquidity The liquidity of the pool after the swap\\n /// @param tick The log base 1.0001 of price of the pool after the swap\\n event Swap(\\n address indexed sender,\\n address indexed recipient,\\n int256 amount0,\\n int256 amount1,\\n uint160 sqrtPriceX96,\\n uint128 liquidity,\\n int24 tick\\n );\\n\\n /// @notice Emitted by the pool for any flashes of token0/token1\\n /// @param sender The address that initiated the swap call, and that received the callback\\n /// @param recipient The address that received the tokens from flash\\n /// @param amount0 The amount of token0 that was flashed\\n /// @param amount1 The amount of token1 that was flashed\\n /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\\n /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\\n event Flash(\\n address indexed sender,\\n address indexed recipient,\\n uint256 amount0,\\n uint256 amount1,\\n uint256 paid0,\\n uint256 paid1\\n );\\n\\n /// @notice Emitted by the pool for increases to the number of observations that can be stored\\n /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\\n /// just before a mint/swap/burn.\\n /// @param observationCardinalityNextOld The previous value of the next observation cardinality\\n /// @param observationCardinalityNextNew The updated value of the next observation cardinality\\n event IncreaseObservationCardinalityNext(\\n uint16 observationCardinalityNextOld,\\n uint16 observationCardinalityNextNew\\n );\\n\\n /// @notice Emitted when the protocol fee is changed by the pool\\n /// @param feeProtocol0Old The previous value of the token0 protocol fee\\n /// @param feeProtocol1Old The previous value of the token1 protocol fee\\n /// @param feeProtocol0New The updated value of the token0 protocol fee\\n /// @param feeProtocol1New The updated value of the token1 protocol fee\\n event SetFeeProtocol(\\n uint8 feeProtocol0Old,\\n uint8 feeProtocol1Old,\\n uint8 feeProtocol0New,\\n uint8 feeProtocol1New\\n );\\n\\n /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\\n /// @param sender The address that collects the protocol fees\\n /// @param recipient The address that receives the collected protocol fees\\n /// @param amount0 The amount of token0 protocol fees that is withdrawn\\n /// @param amount0 The amount of token1 protocol fees that is withdrawn\\n event CollectProtocol(\\n address indexed sender,\\n address indexed recipient,\\n uint128 amount0,\\n uint128 amount1\\n );\\n}\\n\",\"keccak256\":\"0x7209000762e515eceabd42bc2660497d91dfa33099f99d8fc3c55dd1b9578744\",\"license\":\"GPL-2.0-or-later\"},\"contracts/interfaces/uniswap/pool/IUniswapV3PoolImmutables.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-2.0-or-later\\npragma solidity >=0.5.0;\\n\\n/// @title Pool state that never changes\\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\\ninterface IUniswapV3PoolImmutables {\\n /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\\n /// @return The contract address\\n function factory() external view returns (address);\\n\\n /// @notice The first of the two tokens of the pool, sorted by address\\n /// @return The token contract address\\n function token0() external view returns (address);\\n\\n /// @notice The second of the two tokens of the pool, sorted by address\\n /// @return The token contract address\\n function token1() external view returns (address);\\n\\n /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\\n /// @return The fee\\n function fee() external view returns (uint24);\\n\\n /// @notice The pool tick spacing\\n /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\\n /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\\n /// This value is an int24 to avoid casting even though it is always positive.\\n /// @return The tick spacing\\n function tickSpacing() external view returns (int24);\\n\\n /// @notice The maximum amount of position liquidity that can use any tick in the range\\n /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\\n /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\\n /// @return The max amount of liquidity per tick\\n function maxLiquidityPerTick() external view returns (uint128);\\n}\\n\",\"keccak256\":\"0xf6e5d2cd1139c4c276bdbc8e1d2b256e456c866a91f1b868da265c6d2685c3f7\",\"license\":\"GPL-2.0-or-later\"},\"contracts/interfaces/uniswap/pool/IUniswapV3PoolOwnerActions.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-2.0-or-later\\npragma solidity >=0.5.0;\\n\\n/// @title Permissioned pool actions\\n/// @notice Contains pool methods that may only be called by the factory owner\\ninterface IUniswapV3PoolOwnerActions {\\n /// @notice Set the denominator of the protocol's % share of the fees\\n /// @param feeProtocol0 new protocol fee for token0 of the pool\\n /// @param feeProtocol1 new protocol fee for token1 of the pool\\n function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\\n\\n /// @notice Collect the protocol fee accrued to the pool\\n /// @param recipient The address to which collected protocol fees should be sent\\n /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\\n /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\\n /// @return amount0 The protocol fee collected in token0\\n /// @return amount1 The protocol fee collected in token1\\n function collectProtocol(\\n address recipient,\\n uint128 amount0Requested,\\n uint128 amount1Requested\\n ) external returns (uint128 amount0, uint128 amount1);\\n}\\n\",\"keccak256\":\"0x759b78a2918af9e99e246dc3af084f654e48ef32bb4e4cb8a966aa3dcaece235\",\"license\":\"GPL-2.0-or-later\"},\"contracts/interfaces/uniswap/pool/IUniswapV3PoolState.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-2.0-or-later\\npragma solidity >=0.5.0;\\n\\n/// @title Pool state that can change\\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\\n/// per transaction\\ninterface IUniswapV3PoolState {\\n /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\\n /// when accessed externally.\\n /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\\n /// tick The current tick of the pool, i.e. according to the last tick transition that was run.\\n /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\\n /// boundary.\\n /// observationIndex The index of the last oracle observation that was written,\\n /// observationCardinality The current maximum number of observations stored in the pool,\\n /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\\n /// feeProtocol The protocol fee for both tokens of the pool.\\n /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\\n /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\\n /// unlocked Whether the pool is currently locked to reentrancy\\n function slot0()\\n external\\n view\\n returns (\\n uint160 sqrtPriceX96,\\n int24 tick,\\n uint16 observationIndex,\\n uint16 observationCardinality,\\n uint16 observationCardinalityNext,\\n uint8 feeProtocol,\\n bool unlocked\\n );\\n\\n /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\\n /// @dev This value can overflow the uint256\\n function feeGrowthGlobal0X128() external view returns (uint256);\\n\\n /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\\n /// @dev This value can overflow the uint256\\n function feeGrowthGlobal1X128() external view returns (uint256);\\n\\n /// @notice The amounts of token0 and token1 that are owed to the protocol\\n /// @dev Protocol fees will never exceed uint128 max in either token\\n function protocolFees()\\n external\\n view\\n returns (uint128 token0, uint128 token1);\\n\\n /// @notice The currently in range liquidity available to the pool\\n /// @dev This value has no relationship to the total liquidity across all ticks\\n function liquidity() external view returns (uint128);\\n\\n /// @notice Look up information about a specific tick in the pool\\n /// @param tick The tick to look up\\n /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\\n /// tick upper,\\n /// liquidityNet how much liquidity changes when the pool price crosses the tick,\\n /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\\n /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\\n /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\\n /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\\n /// secondsOutside the seconds spent on the other side of the tick from the current tick,\\n /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\\n /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\\n /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\\n /// a specific position.\\n function ticks(int24 tick)\\n external\\n view\\n returns (\\n uint128 liquidityGross,\\n int128 liquidityNet,\\n uint256 feeGrowthOutside0X128,\\n uint256 feeGrowthOutside1X128,\\n int56 tickCumulativeOutside,\\n uint160 secondsPerLiquidityOutsideX128,\\n uint32 secondsOutside,\\n bool initialized\\n );\\n\\n /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\\n function tickBitmap(int16 wordPosition) external view returns (uint256);\\n\\n /// @notice Returns the information about a position by the position's key\\n /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\\n /// @return _liquidity The amount of liquidity in the position,\\n /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\\n /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\\n /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\\n /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\\n function positions(bytes32 key)\\n external\\n view\\n returns (\\n uint128 _liquidity,\\n uint256 feeGrowthInside0LastX128,\\n uint256 feeGrowthInside1LastX128,\\n uint128 tokensOwed0,\\n uint128 tokensOwed1\\n );\\n\\n /// @notice Returns data about a specific observation index\\n /// @param index The element of the observations array to fetch\\n /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\\n /// ago, rather than at a specific index in the array.\\n /// @return blockTimestamp The timestamp of the observation,\\n /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\\n /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\\n /// Returns initialized whether the observation has been initialized and the values are safe to use\\n function observations(uint256 index)\\n external\\n view\\n returns (\\n uint32 blockTimestamp,\\n int56 tickCumulative,\\n uint160 secondsPerLiquidityCumulativeX128,\\n bool initialized\\n );\\n}\\n\",\"keccak256\":\"0x29867ae7524b2ae6581b95abf0c1dd1f697f0494d4c333058a00cdb215f83a43\",\"license\":\"GPL-2.0-or-later\"},\"contracts/libraries/UniswapPricingLibraryV2.sol\":{\"content\":\"pragma solidity >=0.8.0 <0.9.0;\\n// SPDX-License-Identifier: MIT\\n\\n \\n\\nimport {IUniswapPricingLibrary} from \\\"../interfaces/IUniswapPricingLibrary.sol\\\";\\n\\nimport \\\"@openzeppelin/contracts/utils/math/Math.sol\\\";\\n\\n \\nimport \\\"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\\\";\\n\\n// Libraries\\nimport { MathUpgradeable } from \\\"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\\\";\\nimport \\\"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\\\";\\nimport \\\"@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol\\\";\\n\\nimport \\\"../interfaces/uniswap/IUniswapV3Pool.sol\\\"; \\n\\nimport \\\"../libraries/uniswap/TickMath.sol\\\";\\nimport \\\"../libraries/uniswap/FixedPoint96.sol\\\";\\nimport \\\"../libraries/uniswap/FullMath.sol\\\";\\n \\n \\nimport \\\"@openzeppelin/contracts/token/ERC20/IERC20.sol\\\";\\n\\nimport \\\"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\\\";\\n\\n\\n/*\\n\\nOnly do decimal expansion if it is an ERC20 not anything else !! \\n\\n*/\\n\\nlibrary UniswapPricingLibraryV2\\n{\\n \\n uint256 constant STANDARD_EXPANSION_FACTOR = 1e18;\\n\\n \\n function getUniswapPriceRatioForPoolRoutes(\\n IUniswapPricingLibrary.PoolRouteConfig[] memory poolRoutes\\n ) public view returns (uint256 priceRatio) {\\n require(poolRoutes.length <= 2, \\\"invalid pool routes length\\\");\\n\\n if (poolRoutes.length == 2) {\\n uint256 pool0PriceRatio = getUniswapPriceRatioForPool(\\n poolRoutes[0]\\n );\\n\\n uint256 pool1PriceRatio = getUniswapPriceRatioForPool(\\n poolRoutes[1]\\n );\\n\\n return\\n FullMath.mulDiv(\\n pool0PriceRatio,\\n pool1PriceRatio,\\n STANDARD_EXPANSION_FACTOR\\n );\\n } else if (poolRoutes.length == 1) {\\n return getUniswapPriceRatioForPool(poolRoutes[0]);\\n }\\n\\n //else return 0\\n }\\n\\n /*\\n The resultant product is expanded by STANDARD_EXPANSION_FACTOR one time \\n */\\n function getUniswapPriceRatioForPool(\\n IUniswapPricingLibrary.PoolRouteConfig memory _poolRouteConfig\\n ) public view returns (uint256 priceRatio) {\\n\\n \\n\\n // this is expanded by 2**96 or 1e28 \\n uint160 sqrtPriceX96 = getSqrtTwapX96(\\n _poolRouteConfig.pool,\\n _poolRouteConfig.twapInterval\\n );\\n\\n\\n bool invert = ! _poolRouteConfig.zeroForOne; \\n\\n //this output will be expanded by 1e18 \\n return getQuoteFromSqrtRatioX96( sqrtPriceX96 , uint128( STANDARD_EXPANSION_FACTOR ), invert) ;\\n\\n\\n \\n }\\n\\n\\n //taken directly from uniswap oracle lib \\n /**\\n * @dev Calculates the amount of quote token received for a given amount of base token\\n * based on the square root of the price ratio (sqrtRatioX96).\\n *\\n * @param sqrtRatioX96 The square root of the price ratio(in terms of token1/token0) between two tokens, encoded as a Q64.96 value.\\n * @param baseAmount The amount of the base token for which the quote is to be calculated. Specify 1e18 for a price(quoteAmount) with 18 decimals of precision.\\n * @param inverse Specifies the direction of the price quote. If true then baseAmount must be the amount of token1, if false then baseAmount must be the amount for token0\\n *\\n * @return quoteAmount The calculated amount of the quote token for the specified baseAmount\\n */\\n\\n function getQuoteFromSqrtRatioX96(\\n uint160 sqrtRatioX96,\\n uint128 baseAmount,\\n bool inverse\\n ) internal pure returns (uint256 quoteAmount) {\\n // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself\\n if (sqrtRatioX96 <= type(uint128).max) {\\n uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;\\n quoteAmount = !inverse\\n ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)\\n : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);\\n } else {\\n uint256 ratioX128 = FullMath.mulDiv(\\n sqrtRatioX96,\\n sqrtRatioX96,\\n 1 << 64\\n );\\n quoteAmount = !inverse\\n ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)\\n : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);\\n }\\n }\\n \\n\\n function getSqrtTwapX96(address uniswapV3Pool, uint32 twapInterval)\\n internal\\n view\\n returns (uint160 sqrtPriceX96)\\n {\\n if (twapInterval == 0) {\\n // return the current price if twapInterval == 0\\n (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0();\\n } else {\\n uint32[] memory secondsAgos = new uint32[](2);\\n secondsAgos[0] = twapInterval + 1; // from (before)\\n secondsAgos[1] = 1; // one block prior\\n\\n (int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapV3Pool)\\n .observe(secondsAgos);\\n\\n // tick(imprecise as it's an integer) to price\\n sqrtPriceX96 = TickMath.getSqrtRatioAtTick(\\n int24(\\n (tickCumulatives[1] - tickCumulatives[0]) /\\n int32(twapInterval)\\n )\\n );\\n }\\n }\\n\\n function getPriceX96FromSqrtPriceX96(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (uint256 priceX96)\\n { \\n\\n \\n return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96);\\n }\\n\\n}\",\"keccak256\":\"0xd1c349c08c2f602663f1d70df3d59f04861fc123e8c1812a1cfb083ab8f8c2d0\",\"license\":\"MIT\"},\"contracts/libraries/uniswap/FixedPoint96.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-2.0-or-later\\npragma solidity >=0.4.0;\\n\\n/// @title FixedPoint96\\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\\n/// @dev Used in SqrtPriceMath.sol\\nlibrary FixedPoint96 {\\n uint8 internal constant RESOLUTION = 96;\\n uint256 internal constant Q96 = 0x1000000000000000000000000;\\n}\\n\",\"keccak256\":\"0x0ba8a9b95a956a4050749c0158e928398c447c91469682ca8a7cc7e77a7fe032\",\"license\":\"GPL-2.0-or-later\"},\"contracts/libraries/uniswap/FullMath.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\n/// @title Contains 512-bit math functions\\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\\n/// @dev Handles \\\"phantom overflow\\\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\\nlibrary FullMath {\\n /// @notice Calculates floor(a\\u00d7b\\u00f7denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\\n /// @param a The multiplicand\\n /// @param b The multiplier\\n /// @param denominator The divisor\\n /// @return result The 256-bit result\\n /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\\n function mulDiv(uint256 a, uint256 b, uint256 denominator)\\n internal\\n pure\\n returns (uint256 result)\\n {\\n // 512-bit multiply [prod1 prod0] = a * b\\n // Compute the product mod 2**256 and mod 2**256 - 1\\n // then use the Chinese Remainder Theorem to reconstruct\\n // 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(a, b, not(0))\\n prod0 := mul(a, b)\\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 require(denominator > 0);\\n assembly {\\n result := div(prod0, denominator)\\n }\\n return result;\\n }\\n\\n // Make sure the result is less than 2**256.\\n // 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 // Compute remainder using mulmod\\n uint256 remainder;\\n assembly {\\n remainder := mulmod(a, b, denominator)\\n }\\n // Subtract 256 bit number from 512 bit number\\n assembly {\\n prod1 := sub(prod1, gt(remainder, prod0))\\n prod0 := sub(prod0, remainder)\\n }\\n\\n // Factor powers of two out of denominator\\n // Compute largest power of two divisor of denominator.\\n // Always >= 1.\\n // uint256 twos = -denominator & denominator;\\n uint256 twos = (~denominator + 1) & denominator;\\n // Divide denominator by power of two\\n assembly {\\n denominator := div(denominator, twos)\\n }\\n\\n // Divide [prod1 prod0] by the factors of two\\n assembly {\\n prod0 := div(prod0, twos)\\n }\\n // Shift in bits from prod1 into prod0. For this we need\\n // to flip `twos` such that it is 2**256 / twos.\\n // If twos is zero, then it becomes one\\n assembly {\\n twos := add(div(sub(0, twos), twos), 1)\\n }\\n prod0 |= prod1 * twos;\\n\\n // Invert denominator mod 2**256\\n // Now that denominator is an odd number, it has an inverse\\n // modulo 2**256 such that denominator * inv = 1 mod 2**256.\\n // Compute the inverse by starting with a seed that is correct\\n // correct for four bits. That is, denominator * inv = 1 mod 2**4\\n uint256 inv = (3 * denominator) ^ 2;\\n // Now use Newton-Raphson iteration to improve the precision.\\n // Thanks to Hensel's lifting lemma, this also works in modular\\n // arithmetic, doubling the correct bits in each step.\\n inv *= 2 - denominator * inv; // inverse mod 2**8\\n inv *= 2 - denominator * inv; // inverse mod 2**16\\n inv *= 2 - denominator * inv; // inverse mod 2**32\\n inv *= 2 - denominator * inv; // inverse mod 2**64\\n inv *= 2 - denominator * inv; // inverse mod 2**128\\n inv *= 2 - denominator * inv; // inverse mod 2**256\\n\\n // Because the division is now exact we can divide by multiplying\\n // with the modular inverse of denominator. This will give us the\\n // correct result modulo 2**256. Since the precoditions guarantee\\n // that the outcome is less than 2**256, this is the final result.\\n // We don't need to compute the high bits of the result and prod1\\n // is no longer required.\\n result = prod0 * inv;\\n return result;\\n }\\n\\n /// @notice Calculates ceil(a\\u00d7b\\u00f7denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\\n /// @param a The multiplicand\\n /// @param b The multiplier\\n /// @param denominator The divisor\\n /// @return result The 256-bit result\\n function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator)\\n internal\\n pure\\n returns (uint256 result)\\n {\\n result = mulDiv(a, b, denominator);\\n if (mulmod(a, b, denominator) > 0) {\\n require(result < type(uint256).max);\\n result++;\\n }\\n }\\n}\\n\",\"keccak256\":\"0xfb50b2e1fa576851562dd6cebc786506f40f69097955e7c9e3d501899b90c8cd\",\"license\":\"MIT\"},\"contracts/libraries/uniswap/TickMath.sol\":{\"content\":\"// SPDX-License-Identifier: GPL-2.0-or-later\\npragma solidity ^0.8.0;\\n\\n/// @title Math library for computing sqrt prices from ticks and vice versa\\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\\n/// prices between 2**-128 and 2**128\\nlibrary TickMath {\\n /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128\\n int24 internal constant MIN_TICK = -887272;\\n /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128\\n int24 internal constant MAX_TICK = -MIN_TICK;\\n\\n /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\\n uint160 internal constant MIN_SQRT_RATIO = 4295128739;\\n /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\\n uint160 internal constant MAX_SQRT_RATIO =\\n 1461446703485210103287273052203988822378723970342;\\n\\n /// @notice Calculates sqrt(1.0001^tick) * 2^96\\n /// @dev Throws if |tick| > max tick\\n /// @param tick The input tick for the above formula\\n /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\\n /// at the given tick\\n function getSqrtRatioAtTick(int24 tick)\\n internal\\n pure\\n returns (uint160 sqrtPriceX96)\\n {\\n uint256 absTick = tick < 0\\n ? uint256(-int256(tick))\\n : uint256(int256(tick));\\n require(absTick <= uint256(uint24(MAX_TICK)), \\\"T\\\");\\n\\n uint256 ratio = absTick & 0x1 != 0\\n ? 0xfffcb933bd6fad37aa2d162d1a594001\\n : 0x100000000000000000000000000000000;\\n if (absTick & 0x2 != 0)\\n ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\\n if (absTick & 0x4 != 0)\\n ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\\n if (absTick & 0x8 != 0)\\n ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\\n if (absTick & 0x10 != 0)\\n ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\\n if (absTick & 0x20 != 0)\\n ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\\n if (absTick & 0x40 != 0)\\n ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\\n if (absTick & 0x80 != 0)\\n ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\\n if (absTick & 0x100 != 0)\\n ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\\n if (absTick & 0x200 != 0)\\n ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\\n if (absTick & 0x400 != 0)\\n ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\\n if (absTick & 0x800 != 0)\\n ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\\n if (absTick & 0x1000 != 0)\\n ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\\n if (absTick & 0x2000 != 0)\\n ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\\n if (absTick & 0x4000 != 0)\\n ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\\n if (absTick & 0x8000 != 0)\\n ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\\n if (absTick & 0x10000 != 0)\\n ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\\n if (absTick & 0x20000 != 0)\\n ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\\n if (absTick & 0x40000 != 0)\\n ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\\n if (absTick & 0x80000 != 0)\\n ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\\n\\n if (tick > 0) ratio = type(uint256).max / ratio;\\n\\n // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\\n // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\\n // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\\n sqrtPriceX96 = uint160(\\n (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)\\n );\\n }\\n\\n /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\\n /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\\n /// ever return.\\n /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\\n /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\\n function getTickAtSqrtRatio(uint160 sqrtPriceX96)\\n internal\\n pure\\n returns (int24 tick)\\n {\\n // second inequality must be < because the price can never reach the price at the max tick\\n require(\\n sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO,\\n \\\"R\\\"\\n );\\n uint256 ratio = uint256(sqrtPriceX96) << 32;\\n\\n uint256 r = ratio;\\n uint256 msb = 0;\\n\\n assembly {\\n let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\\n msb := or(msb, f)\\n r := shr(f, r)\\n }\\n assembly {\\n let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))\\n msb := or(msb, f)\\n r := shr(f, r)\\n }\\n assembly {\\n let f := shl(5, gt(r, 0xFFFFFFFF))\\n msb := or(msb, f)\\n r := shr(f, r)\\n }\\n assembly {\\n let f := shl(4, gt(r, 0xFFFF))\\n msb := or(msb, f)\\n r := shr(f, r)\\n }\\n assembly {\\n let f := shl(3, gt(r, 0xFF))\\n msb := or(msb, f)\\n r := shr(f, r)\\n }\\n assembly {\\n let f := shl(2, gt(r, 0xF))\\n msb := or(msb, f)\\n r := shr(f, r)\\n }\\n assembly {\\n let f := shl(1, gt(r, 0x3))\\n msb := or(msb, f)\\n r := shr(f, r)\\n }\\n assembly {\\n let f := gt(r, 0x1)\\n msb := or(msb, f)\\n }\\n\\n if (msb >= 128) r = ratio >> (msb - 127);\\n else r = ratio << (127 - msb);\\n\\n int256 log_2 = (int256(msb) - 128) << 64;\\n\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(63, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(62, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(61, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(60, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(59, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(58, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(57, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(56, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(55, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(54, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(53, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(52, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(51, f))\\n r := shr(f, r)\\n }\\n assembly {\\n r := shr(127, mul(r, r))\\n let f := shr(128, r)\\n log_2 := or(log_2, shl(50, f))\\n }\\n\\n int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\\n\\n int24 tickLow = int24(\\n (log_sqrt10001 - 3402992956809132418596140100660247210) >> 128\\n );\\n int24 tickHi = int24(\\n (log_sqrt10001 + 291339464771989622907027621153398088495) >> 128\\n );\\n\\n tick = tickLow == tickHi\\n ? tickLow\\n : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96\\n ? tickHi\\n : tickLow;\\n }\\n}\\n\",\"keccak256\":\"0xf98bbfc8977090f026ee4b8389bb1e2e903eb0575fceea10edb373f33d51d013\",\"license\":\"GPL-2.0-or-later\"}},\"version\":1}", + "bytecode": "0x610fd461003a600b82828239805160001a60731461002d57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610adb565b61007d565b60405190815260200160405180910390f35b610058610078366004610b1b565b6100b6565b60008061009283600001518460400151610198565b6020840151909150156100ae82670de0b6b3a76400008361036f565b949350505050565b600060028251111561010f5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b81516002141561016d57600061013e8360008151811061013157610131610bba565b602002602001015161007d565b905060006101588460018151811061013157610131610bba565b90506100ae8282670de0b6b3a7640000610449565b8151600114156101935761018d8260008151811061013157610131610bba565b92915050565b919050565b600063ffffffff821661021657826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156101e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102079190610be2565b5094955061018d945050505050565b604080516002808252606082018352600092602083019080368337019050509050610242836001610c97565b8160008151811061025557610255610bba565b602002602001019063ffffffff16908163ffffffff168152505060018160018151811061028457610284610bba565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd906102c8908590600401610cbf565b600060405180830381865afa1580156102e5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261030d9190810190610d78565b5090506103668460030b8260008151811061032a5761032a610bba565b60200260200101518360018151811061034557610345610bba565b60200260200101516103579190610e44565b6103619190610eaa565b6105c3565b95945050505050565b60006001600160801b036001600160a01b038516116103e257600061039d6001600160a01b03861680610ee8565b905082156103c2576103bd600160c01b856001600160801b031683610449565b6103da565b6103da81856001600160801b0316600160c01b610449565b915050610442565b60006104016001600160a01b0386168068010000000000000000610449565b9050821561042657610421600160801b856001600160801b031683610449565b61043e565b61043e81856001600160801b0316600160801b610449565b9150505b9392505050565b600080806000198587098587029250828110838203039150508060001415610483576000841161047857600080fd5b508290049050610442565b80841161048f57600080fd5b6000848688098084039381119092039190506000856104b081196001610f07565b169586900495938490049360008190030460010190506104d08184610ee8565b9093179260006104e1876003610ee8565b60021890506104f08188610ee8565b6104fb906002610f1f565b6105059082610ee8565b90506105118188610ee8565b61051c906002610f1f565b6105269082610ee8565b90506105328188610ee8565b61053d906002610f1f565b6105479082610ee8565b90506105538188610ee8565b61055e906002610f1f565b6105689082610ee8565b90506105748188610ee8565b61057f906002610f1f565b6105899082610ee8565b90506105958188610ee8565b6105a0906002610f1f565b6105aa9082610ee8565b90506105b68186610ee8565b9998505050505050505050565b60008060008360020b126105da578260020b6105e7565b8260020b6105e790610f36565b90506105f6620d89e719610f53565b62ffffff1681111561062e5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610106565b60006001821661064257600160801b610654565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561069357608061068e826ffff97272373d413259a46990580e213a610ee8565b901c90505b60048216156106bd5760806106b8826ffff2e50f5f656932ef12357cf3c7fdcc610ee8565b901c90505b60088216156106e75760806106e2826fffe5caca7e10e4e61c3624eaa0941cd0610ee8565b901c90505b601082161561071157608061070c826fffcb9843d60f6159c9db58835c926644610ee8565b901c90505b602082161561073b576080610736826fff973b41fa98c081472e6896dfb254c0610ee8565b901c90505b6040821615610765576080610760826fff2ea16466c96a3843ec78b326b52861610ee8565b901c90505b608082161561078f57608061078a826ffe5dee046a99a2a811c461f1969c3053610ee8565b901c90505b6101008216156107ba5760806107b5826ffcbe86c7900a88aedcffc83b479aa3a4610ee8565b901c90505b6102008216156107e55760806107e0826ff987a7253ac413176f2b074cf7815e54610ee8565b901c90505b61040082161561081057608061080b826ff3392b0822b70005940c7a398e4b70f3610ee8565b901c90505b61080082161561083b576080610836826fe7159475a2c29b7443b29c7fa6e889d9610ee8565b901c90505b611000821615610866576080610861826fd097f3bdfd2022b8845ad8f792aa5825610ee8565b901c90505b61200082161561089157608061088c826fa9f746462d870fdf8a65dc1f90e061e5610ee8565b901c90505b6140008216156108bc5760806108b7826f70d869a156d2a1b890bb3df62baf32f7610ee8565b901c90505b6180008216156108e75760806108e2826f31be135f97d08fd981231505542fcfa6610ee8565b901c90505b6201000082161561091357608061090e826f09aa508b5b7a84e1c677de54f3e99bc9610ee8565b901c90505b6202000082161561093e576080610939826e5d6af8dedb81196699c329225ee604610ee8565b901c90505b62040000821615610968576080610963826d2216e584f5fa1ea926041bedfe98610ee8565b901c90505b6208000082161561099057608061098b826b048a170391f7dc42444e8fa2610ee8565b901c90505b60008460020b13156109ab576109a881600019610f76565b90505b6109ba64010000000082610f8a565b156109c65760016109c9565b60005b6100ae9060ff16602083901c610f07565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a1957610a196109da565b604052919050565b6001600160a01b0381168114610a3657600080fd5b50565b8015158114610a3657600080fd5b600060a08284031215610a5957600080fd5b60405160a0810181811067ffffffffffffffff82111715610a7c57610a7c6109da565b6040529050808235610a8d81610a21565b81526020830135610a9d81610a39565b6020820152604083013563ffffffff81168114610ab957600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610aed57600080fd5b6104428383610a47565b600067ffffffffffffffff821115610b1157610b116109da565b5060051b60200190565b60006020808385031215610b2e57600080fd5b823567ffffffffffffffff811115610b4557600080fd5b8301601f81018513610b5657600080fd5b8035610b69610b6482610af7565b6109f0565b81815260a09182028301840191848201919088841115610b8857600080fd5b938501935b83851015610bae57610b9f8986610a47565b83529384019391850191610b8d565b50979650505050505050565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461019357600080fd5b600080600080600080600060e0888a031215610bfd57600080fd5b8751610c0881610a21565b8097505060208801518060020b8114610c2057600080fd5b9550610c2e60408901610bd0565b9450610c3c60608901610bd0565b9350610c4a60808901610bd0565b925060a088015160ff81168114610c6057600080fd5b60c0890151909250610c7181610a39565b8091505092959891949750929550565b634e487b7160e01b600052601160045260246000fd5b600063ffffffff808316818516808303821115610cb657610cb6610c81565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cfd57835163ffffffff1683529284019291840191600101610cdb565b50909695505050505050565b600082601f830112610d1a57600080fd5b81516020610d2a610b6483610af7565b82815260059290921b84018101918181019086841115610d4957600080fd5b8286015b84811015610d6d578051610d6081610a21565b8352918301918301610d4d565b509695505050505050565b60008060408385031215610d8b57600080fd5b825167ffffffffffffffff80821115610da357600080fd5b818501915085601f830112610db757600080fd5b81516020610dc7610b6483610af7565b82815260059290921b84018101918181019089841115610de657600080fd5b948201945b83861015610e145785518060060b8114610e055760008081fd5b82529482019490820190610deb565b91880151919650909350505080821115610e2d57600080fd5b50610e3a85828601610d09565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e6f57610e6f610c81565b81667fffffffffffff018313811615610e8a57610e8a610c81565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610ec157610ec1610e94565b667fffffffffffff19821460001982141615610edf57610edf610c81565b90059392505050565b6000816000190483118215151615610f0257610f02610c81565b500290565b60008219821115610f1a57610f1a610c81565b500190565b600082821015610f3157610f31610c81565b500390565b6000600160ff1b821415610f4c57610f4c610c81565b5060000390565b60008160020b627fffff19811415610f6d57610f6d610c81565b60000392915050565b600082610f8557610f85610e94565b500490565b600082610f9957610f99610e94565b50069056fea26469706673582212201c309f787d80bdc12eabe279cffec7e7a313501dad51a960efbf93262049393964736f6c634300080b0033", + "deployedBytecode": "0x73000000000000000000000000000000000000000030146080604052600436106100405760003560e01c80631217931b14610045578063caf0f0331461006a575b600080fd5b610058610053366004610adb565b61007d565b60405190815260200160405180910390f35b610058610078366004610b1b565b6100b6565b60008061009283600001518460400151610198565b6020840151909150156100ae82670de0b6b3a76400008361036f565b949350505050565b600060028251111561010f5760405162461bcd60e51b815260206004820152601a60248201527f696e76616c696420706f6f6c20726f75746573206c656e67746800000000000060448201526064015b60405180910390fd5b81516002141561016d57600061013e8360008151811061013157610131610bba565b602002602001015161007d565b905060006101588460018151811061013157610131610bba565b90506100ae8282670de0b6b3a7640000610449565b8151600114156101935761018d8260008151811061013157610131610bba565b92915050565b919050565b600063ffffffff821661021657826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa1580156101e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102079190610be2565b5094955061018d945050505050565b604080516002808252606082018352600092602083019080368337019050509050610242836001610c97565b8160008151811061025557610255610bba565b602002602001019063ffffffff16908163ffffffff168152505060018160018151811061028457610284610bba565b63ffffffff9092166020928302919091019091015260405163883bdbfd60e01b81526000906001600160a01b0386169063883bdbfd906102c8908590600401610cbf565b600060405180830381865afa1580156102e5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261030d9190810190610d78565b5090506103668460030b8260008151811061032a5761032a610bba565b60200260200101518360018151811061034557610345610bba565b60200260200101516103579190610e44565b6103619190610eaa565b6105c3565b95945050505050565b60006001600160801b036001600160a01b038516116103e257600061039d6001600160a01b03861680610ee8565b905082156103c2576103bd600160c01b856001600160801b031683610449565b6103da565b6103da81856001600160801b0316600160c01b610449565b915050610442565b60006104016001600160a01b0386168068010000000000000000610449565b9050821561042657610421600160801b856001600160801b031683610449565b61043e565b61043e81856001600160801b0316600160801b610449565b9150505b9392505050565b600080806000198587098587029250828110838203039150508060001415610483576000841161047857600080fd5b508290049050610442565b80841161048f57600080fd5b6000848688098084039381119092039190506000856104b081196001610f07565b169586900495938490049360008190030460010190506104d08184610ee8565b9093179260006104e1876003610ee8565b60021890506104f08188610ee8565b6104fb906002610f1f565b6105059082610ee8565b90506105118188610ee8565b61051c906002610f1f565b6105269082610ee8565b90506105328188610ee8565b61053d906002610f1f565b6105479082610ee8565b90506105538188610ee8565b61055e906002610f1f565b6105689082610ee8565b90506105748188610ee8565b61057f906002610f1f565b6105899082610ee8565b90506105958188610ee8565b6105a0906002610f1f565b6105aa9082610ee8565b90506105b68186610ee8565b9998505050505050505050565b60008060008360020b126105da578260020b6105e7565b8260020b6105e790610f36565b90506105f6620d89e719610f53565b62ffffff1681111561062e5760405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606401610106565b60006001821661064257600160801b610654565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff169050600282161561069357608061068e826ffff97272373d413259a46990580e213a610ee8565b901c90505b60048216156106bd5760806106b8826ffff2e50f5f656932ef12357cf3c7fdcc610ee8565b901c90505b60088216156106e75760806106e2826fffe5caca7e10e4e61c3624eaa0941cd0610ee8565b901c90505b601082161561071157608061070c826fffcb9843d60f6159c9db58835c926644610ee8565b901c90505b602082161561073b576080610736826fff973b41fa98c081472e6896dfb254c0610ee8565b901c90505b6040821615610765576080610760826fff2ea16466c96a3843ec78b326b52861610ee8565b901c90505b608082161561078f57608061078a826ffe5dee046a99a2a811c461f1969c3053610ee8565b901c90505b6101008216156107ba5760806107b5826ffcbe86c7900a88aedcffc83b479aa3a4610ee8565b901c90505b6102008216156107e55760806107e0826ff987a7253ac413176f2b074cf7815e54610ee8565b901c90505b61040082161561081057608061080b826ff3392b0822b70005940c7a398e4b70f3610ee8565b901c90505b61080082161561083b576080610836826fe7159475a2c29b7443b29c7fa6e889d9610ee8565b901c90505b611000821615610866576080610861826fd097f3bdfd2022b8845ad8f792aa5825610ee8565b901c90505b61200082161561089157608061088c826fa9f746462d870fdf8a65dc1f90e061e5610ee8565b901c90505b6140008216156108bc5760806108b7826f70d869a156d2a1b890bb3df62baf32f7610ee8565b901c90505b6180008216156108e75760806108e2826f31be135f97d08fd981231505542fcfa6610ee8565b901c90505b6201000082161561091357608061090e826f09aa508b5b7a84e1c677de54f3e99bc9610ee8565b901c90505b6202000082161561093e576080610939826e5d6af8dedb81196699c329225ee604610ee8565b901c90505b62040000821615610968576080610963826d2216e584f5fa1ea926041bedfe98610ee8565b901c90505b6208000082161561099057608061098b826b048a170391f7dc42444e8fa2610ee8565b901c90505b60008460020b13156109ab576109a881600019610f76565b90505b6109ba64010000000082610f8a565b156109c65760016109c9565b60005b6100ae9060ff16602083901c610f07565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610a1957610a196109da565b604052919050565b6001600160a01b0381168114610a3657600080fd5b50565b8015158114610a3657600080fd5b600060a08284031215610a5957600080fd5b60405160a0810181811067ffffffffffffffff82111715610a7c57610a7c6109da565b6040529050808235610a8d81610a21565b81526020830135610a9d81610a39565b6020820152604083013563ffffffff81168114610ab957600080fd5b8060408301525060608301356060820152608083013560808201525092915050565b600060a08284031215610aed57600080fd5b6104428383610a47565b600067ffffffffffffffff821115610b1157610b116109da565b5060051b60200190565b60006020808385031215610b2e57600080fd5b823567ffffffffffffffff811115610b4557600080fd5b8301601f81018513610b5657600080fd5b8035610b69610b6482610af7565b6109f0565b81815260a09182028301840191848201919088841115610b8857600080fd5b938501935b83851015610bae57610b9f8986610a47565b83529384019391850191610b8d565b50979650505050505050565b634e487b7160e01b600052603260045260246000fd5b805161ffff8116811461019357600080fd5b600080600080600080600060e0888a031215610bfd57600080fd5b8751610c0881610a21565b8097505060208801518060020b8114610c2057600080fd5b9550610c2e60408901610bd0565b9450610c3c60608901610bd0565b9350610c4a60808901610bd0565b925060a088015160ff81168114610c6057600080fd5b60c0890151909250610c7181610a39565b8091505092959891949750929550565b634e487b7160e01b600052601160045260246000fd5b600063ffffffff808316818516808303821115610cb657610cb6610c81565b01949350505050565b6020808252825182820181905260009190848201906040850190845b81811015610cfd57835163ffffffff1683529284019291840191600101610cdb565b50909695505050505050565b600082601f830112610d1a57600080fd5b81516020610d2a610b6483610af7565b82815260059290921b84018101918181019086841115610d4957600080fd5b8286015b84811015610d6d578051610d6081610a21565b8352918301918301610d4d565b509695505050505050565b60008060408385031215610d8b57600080fd5b825167ffffffffffffffff80821115610da357600080fd5b818501915085601f830112610db757600080fd5b81516020610dc7610b6483610af7565b82815260059290921b84018101918181019089841115610de657600080fd5b948201945b83861015610e145785518060060b8114610e055760008081fd5b82529482019490820190610deb565b91880151919650909350505080821115610e2d57600080fd5b50610e3a85828601610d09565b9150509250929050565b60008160060b8360060b6000811281667fffffffffffff1901831281151615610e6f57610e6f610c81565b81667fffffffffffff018313811615610e8a57610e8a610c81565b5090039392505050565b634e487b7160e01b600052601260045260246000fd5b60008160060b8360060b80610ec157610ec1610e94565b667fffffffffffff19821460001982141615610edf57610edf610c81565b90059392505050565b6000816000190483118215151615610f0257610f02610c81565b500290565b60008219821115610f1a57610f1a610c81565b500190565b600082821015610f3157610f31610c81565b500390565b6000600160ff1b821415610f4c57610f4c610c81565b5060000390565b60008160020b627fffff19811415610f6d57610f6d610c81565b60000392915050565b600082610f8557610f85610e94565b500490565b600082610f9957610f99610e94565b50069056fea26469706673582212201c309f787d80bdc12eabe279cffec7e7a313501dad51a960efbf93262049393964736f6c634300080b0033", + "devdoc": { + "kind": "dev", + "methods": {}, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file From c84f337d33948947ddc550834df33f52231afc8b Mon Sep 17 00:00:00 2001 From: andy Date: Fri, 4 Apr 2025 13:01:46 -0400 Subject: [PATCH 6/6] max principal --- .../LenderCommitmentForwarder_U2.sol | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol b/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol index f9ebf18cb..9051cd7b1 100644 --- a/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol +++ b/packages/contracts/contracts/LenderCommitmentForwarder/LenderCommitmentForwarder_U2.sol @@ -669,6 +669,13 @@ contract LenderCommitmentForwarder_U2 is return 0; } + + //if we would divide by zero, return infinite + if (_maxPrincipalPerCollateralAmount == 0 ){ + return type(uint256).max; + } + + if (_collateralTokenType == CommitmentCollateralType.ERC20) { return MathUpgradeable.mulDiv(